假设我有一个像这样的json:
[
{
id: 3,
name: 'A',
depth:0
},
{
id: 2,
name: 'C'
depth:1
},
{
id: 3,
name: 'B',
depth:1
},
{
id: 1,
name: 'Z'
},
{
id: 2,
name: 'F',
depth:0
}
]
我想要做的是使用这些规则创建另一个对象数组:
1:在数组中找到相同的ID
2:检查深度(因此,如果depth为0,则应为父级;如果depth为1,则应为深度为0的元素的子级)
像这样:
[
{
id: 3,
name: 'A',
depth:0,
child:[
{
id: 3,
name: 'B',
depth:1
},
]
},
{
id: 1,
name: 'Z'
},
{
id: 2,
name: 'F',
depth:0,
child:[
{
id: 2,
name: 'C',
depth:1,
},
]
}
]
有什么帮助吗?
答案 0 :(得分:0)
你在这里..
var a = [
{
id: 3,
name: 'A',
depth:0
},
{
id: 2,
name: 'C',
depth:1
},
{
id: 3,
name: 'B',
depth:1
},
{
id: 1,
name: 'Z'
},
{
id: 2,
name: 'F',
depth:0
}]
var c = a.filter(a => a.depth == 0);
var zeroDepth = a.filter(a => a.depth === undefined);
zeroDepth.forEach(z => c.push(z));
a.forEach(a =>
{
if(a.depth == 1){
c.forEach(c =>
{
if(c.id == a.id){
c.child = [];
c.child.push(a);
}
})
}
})
console.log(c);