这是嵌套数组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);
}
}
}
答案 0 :(得分:0)
似乎是一个非常简单的地图/减少工作。只需迭代parents
数组并将children
数组映射到data.grandparent_id
,parent.parent_id
和child.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)