我很难弄清楚如何执行这个递归映射函数。
我有一个看起来像这样的数组。
var array = [
{
id: 1,
label: 'Satisfied customers',
children: [
{
id: 2,
label: 'Good food',
icon: 'restaurant_menu',
children: [
{ id: 3, label: 'Quality ingredients'},
{ id: 4, label: 'Good recipe' }
]
},
{
id: 5,
label: 'Good service',
icon: 'room_service',
children: [
{ id: 6, label: 'Prompt attention' },
{ id: 7, label: 'Professional waiter' }
]
},
{
id: 8,
label: 'Pleasant surroundings',
icon: 'photo',
children: [
{
id: 9,
label: 'Happy atmosphere (not tickable)',
tickable: false,
},
{
id: 10,
label: 'Good table presentation (disabled node)',
disabled: true,
},
{
id: 11,
label: 'Pleasing decor',
}
]
},
{
id: 12,
label: 'Extra information (has no tick)',
noTick: true,
icon: 'photo'
},
{
id: 13,
label: 'Forced tick strategy (to "strict" in this case)',
tickStrategy: 'strict',
icon: 'school',
children: [
{
id: 14,
label: 'Happy atmosphere',
},
{
id: 15,
label: 'Good table presentation',
},
{
id: 16,
label: 'Very pleasing decor',
}
]
}
]
}
];
这是数组的样子......
![enter image description here](https://i.sstatic.net/FkAMm.png)
如您所见, children 是
recursive
.我需要将它们放入一个数组中。
我的代码不起作用并且有错误。
const result = [];
const map = (e) => {
result.push({
id: e.id,
label: e.label,
})
e.children.map(map)
};
array.map(map);
错误出现在
e.children.map(map)
.![enter image description here](https://i.sstatic.net/MD4YV.png)
我需要将它们全部推送到数组变量中,但我不知道该怎么做。泰
最佳答案
您需要检查当前项目是否有 children
元素,您可以使用 forEach
而是因为 map
返回新数组和 forEach
只是去扔每个元素。
const cb = (e) => {
res.push({
id: e.id,
label: e.label,
});
e.children && e.children.forEach(cb);
}
array.forEach(cb);
关于javascript - 递归映射函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54245284/