我想为以下json做foreach:-
const TREE_DATA: FoodNode[] = [
{
name: 'Fruit',
children: [
{name: 'Apple'},
{name: 'Banana'},
{name: 'Fruit loops'},
]
}, {
name: 'Vegetables',
children: [
{
name: 'Green',
children: [
{name: 'Broccoli'},
{name: 'Brussel sprouts'},
]
}, {
name: 'Orange',
children: [
{name: 'Pumpkins'},
{name: 'Carrots'},
]
},
]
},
];
答案 0 :(得分:1)
您需要使用递归函数
showData(element,level,parent)
{
element.forEach(x=>
{
x.level=level
x.parent=parent
console.log(x.name,x.level,x.parent);
if (x.children)
this.showData(x.children,x.level+1,x.name)
})
}
您致电为
this.showData(TREE_DATA,0,null)
看到我们在数据“级别”和我们可以使用的“父”中添加了两个新属性