遍历树并推送数组中的所有属性

时间:2017-04-05 20:51:52

标签: javascript arrays tree

var obj = {
    x1: {
        x2: {
            x3: {
                condition: false,
                condition_trust: 55.25,
                condition_2 : true,
                condition_2_trust: 56.456
            }
        },
        x4: {
            name: "aaa",
            name_trust: 55.25,
            name_2: "bbb",
            name_2_trust: 96.42
        }
    }
}

我有一棵这样的树,它更复杂,更深,更大。属性始终位于最后一级。

我要做的是获取所有属性及其值并将它们推入新数组中。基本上我试图得到这样的数组:

array = [
x1_x2_x3_condition : false,
x1_x2_x3_condition_trust : 55.25,
x1_x2_x3_condition_2 : true,
x1_x2_x3_condition_2_trust : 55.456,
x4_name : "aaa",
x4_name_trust : 55.25,
x4_name_2 : "bbb",
x4_name_2_trust : 96.42
]

我不知道从哪里开始。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

基本上你需要压扁物体?如果是这样,这是解决方案



var obj = {
  x1: {
    x2: {
      x3: {
        condition: false,
        condition_trust: 55.25,
        condition_2: true,
        condition_2_trust: 56.456
      }
    },
    x4: {
      name: "aaa",
      name_trust: 55.25,
      name_2: "bbb",
      name_2_trust: 96.42
    }
  }
}

function flattenObject(obj) {
  return Object.keys(obj).reduce(function(a, k) {
    if (obj[k].constructor === Object) {
      var o = flattenObject(obj[k]);
      Object.keys(o).forEach(function(key) {
        a[k + '_' + key] = o[key];
      });
    } else {
      a[k] = obj[k];
    }
    return a;
  }, {});
}

console.log(flattenObject(obj));