我正在寻找一种递归方法,该方法将为我提供所有带有孩子的物品的数量。
当我发现一个项目有孩子时,我目前正深入三个层次并增加一个计数器。
但是,我希望能够递归检查数组中是否没有子级。
[
{
id: 2,
name: 'parent',
children: [
{
id: 12,
name: 'firstChild',
children: [
{
id: 22,
name: 'firstGrandChild',
children: [
{
id: 32,
name: 'GreatGrandChild',
children: []
}
]
}
]
},
{
id: 3,
name: 'secondRowFirstChild',
children: [
{
id: 13,
name: 'secondRowGrandChild',
children: []
}
]
},
{
id: 4,
name: 'thirdRowFirstChild',
children: [
{
id: 14,
name: 'thirdRowGrandChild',
children: []
}
]
}
]
}
]
// Here is the procedural code that I want to convert
getExpandableRowCount(items: TableRow[]): number {
let count = 0
items.map(item => {
if (item.children && item.children.length) {
count++;
item.children.map(subItem => {
if (subItem.children && subItem.children.length) {
count++;
subItem.children.map(subSubItem => {
if (subSubItem.children && subSubItem.children.length) {
count++;
}
})
}
})
}
});
return count;
}
我希望这个数字是5。
答案 0 :(得分:0)
您可以使用Array.reduce()
,并且如果某项的children
的长度大于0,则将其加1,在其上调用count
,然后将其总计:
const count = arr => arr.reduce((r, { children = [] }) =>
children.length ? r + 1 + count(children) : r
, 0)
const data = [{"id":2,"name":"parent","children":[{"id":12,"name":"firstChild","children":[{"id":22,"name":"firstGrandChild","children":[{"id":32,"name":"GreatGrandChild","children":[]}]}]},{"id":3,"name":"secondRowFirstChild","children":[{"id":13,"name":"secondRowGrandChild","children":[]}]},{"id":4,"name":"thirdRowFirstChild","children":[{"id":14,"name":"thirdRowGrandChild","children":[]}]}]}]
const result = count(data)
console.log(result)