如何使用递归函数动态地将嵌套数组对象转换为平面表angularjs?

时间:2017-02-28 22:55:00

标签: javascript

这是嵌套数组Object示例。如何以递归方式将父元素附加到表的子元素?

请注意:嵌套对象中可以有n个级别

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,   
                  "smallchildren": [
              {
              "smallchild_id": 465
              },
              {
              "smallchild_id": 466
              },
              {
              "smallchild_id": 467
              }
              ]
  }    
  ]
  }
]
}

预期产出:

var resultArray = [[7,65,365],[7,66,365],[7,66,366],[7,66,367]]
Grandparent_id|parent_id|child_id
7             |65       |365
7             |66       |365
7             |66       |366   
7             |66       |367

试过这个:

 function normalize(parent) {
    if (parent && parent.children) {
        for (var i = 0, l = parent.children.length; i < l; ++i) {
            var child = parent.children[i];
            child.index = i;
            if (!child.parentId) child.parentId = parent.id || '0';
            normalize(child);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

似乎是一个非常简单的地图/减少工作。只需迭代parents数组并将children数组映射到data.grandparent_idparent.parent_idchild.child_id的数组中。

const 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}]}]}

const resultArray = data.parents.reduce((arr, parent) => {
  return arr.concat(parent.children.map(child =>
    [data.grandparent_id, parent.parent_id, child.child_id]))
}, [])

console.info('resultArray =', JSON.stringify(resultArray))

如果您希望内部数组是对象,只需更改map返回值...

const 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}]}]}

const resultArray = data.parents.reduce((arr, parent) => {
  return arr.concat(parent.children.map(child => ({
    grandparent_id: data.grandparent_id,
    parent_id: parent.parent_id,
    child_id: child.child_id
  })))
}, [])

console.info('resultArray =', resultArray)