根据索引值组合父级和chid JSON数组,然后向其添加另一个发现的属性。
数据:比较字段:
parentJSON-索引
childJSON-parent_index
输出:
-父母
-及其孩子
-父母
-及其孩子
parentJSON:
[{ index:1, name: 'a'}, {index:2, name: 'b'}, {index:3, name: 'c'}, {index:4, name: 'd'}]
childJSON:
[
{ index:1, name: 'aa', parent_index:1},
{index:2, name: 'ab', parent_index:1},
{index:3, name: 'ba', parent_index: 2},
{index:4, name: 'bb', parent_index: 2},
{index:5, name: 'ca', parent_index: 3},
{index:6, name: 'ad', parent_index: 1}
]
output:
[
{ index:1, name: 'a'},
{ index:1, name: 'aa', parent_index:1, found: true},
{ index:2, name: 'ab', parent_index:1, found: true},
{ index:6, name: 'ad', parent_index:1, found: true},
{ index:2, name: 'b'},
{ index:3, name: 'ba', parent_index:2, found: true},
{ index:4, name: 'bb', parent_index:2, found: true},
{ index:3, name: 'c'},
{ index:5, name: 'ca', parent_index:3, found: true},
{ index:4, name: 'd'},
]
Plunker Link
最佳答案
let parentJSON =
[{ index:1, name: 'a'}, {index:2, name: 'b'}, {index:3, name: 'c'}, {index:4, name: 'd'}]
let childJSON =
[
{ index:1, name: 'aa', parent_index:1},
{index:2, name: 'ab', parent_index:1},
{index:3, name: 'ba', parent_index: 2},
{index:4, name: 'bb', parent_index: 2},
{index:5, name: 'ca', parent_index: 3},
{index:6, name: 'ad', parent_index: 1}
]
let answer = [];
parentJSON.forEach(parent => {
answer.push(parent);
childJSON.forEach(child => {
if(child.parent_index === parent.index){
child.found = true;
answer.push(child);
}
})
});
console.log(answer)
在不知道您如何期望
childJSON
在parentJSON
中不存在的情况下,上述解决方案假设childJSON
的所有元素都有指向parent_index
的parentJSON
链接。如果您更新了问题,请告诉我,除非这正是您想要的
关于javascript - 使用lodash创建父子关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50519730/