在 Javascript/Typescript/ES6 中递归计算子项的数量



我正在寻找一种递归方法,它可以为我提供所有带有子项的计数。

我目前只是在看三级深,当我发现一个项目有孩子时,我会增加一个计数器。

但是,我希望能够递归检查,直到数组中没有子项。

[
    {
        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。

您可以使用 Array.reduce() ,如果项目的长度大于 0 的 children,则添加 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)

最新更新