如何递归遍历嵌套对象并生成对象数组?

时间:2017-03-01 21:45:35

标签: javascript angularjs

这是嵌套数组Object示例。如何递归遍历并生成一个对象数组?

var data = {
      "grandparent_id": 7,
      "parents": [
        {
          "parent_id": 65,
          "children": [
            {
              "child_id": 365
            }
          ]
        },
        {
          "parent_id": 66,
          "children": [
            {
              "child_id": 365
            },
            {
              "child_id": 366
            },
            {
              "child_id": 367
            }
          ]
        }
      ]
    }

预期产出:

[{grandparent_id:'7',parent_id:'65',child_id:'365'},{grandparent_id:'7',parent_id:'66',child_id:'365'},{grandparent_id:'7',parent_id:'66',child_id:'366'},{grandparent_id:'7',parent_id:'66',child_id:'367'}]

试过这个但没有让它起作用:

var data1 = [];
for (var i=0; i<data.parents.length;i++) {

  for (var j=0; j<data.parents.children.length;j++){
  data1.push({ grandparent_id: data.grandparent_id, parent_id: data.parent[i].parent_id, child_id: data.parent.children[j] });
  }
}

1 个答案:

答案 0 :(得分:0)

您需要正确访问子项,并使用toString方法获取字符串值。

var data = { grandparent_id: 7, parents: [{ parent_id: 65, children: [{ child_id: 365 }] }, { parent_id: 66, children: [{ child_id: 365 }, { child_id: 366 }, { child_id: 367 }] }] },
    data1 = [];

for (var i = 0; i < data.parents.length; i++) {
    for (var j = 0; j < data.parents[i].children.length; j++) {
    //                              ^^^
        data1.push({
            grandparent_id: data.grandparent_id.toString(),
            parent_id: data.parents[i].parent_id.toString(),
            //                    ^
            child_id: data.parents[i].children[j].child_id.toString()
            //                   ^^^^            ^^^^^^^^^
        });
    }
}

console.log(data1);
.as-console-wrapper { max-height: 100% !important; top: 0; }