Я ищу рекурсивный метод, который бы подсчитывал все элементы с детьми.
В настоящее время я просто заглядываю на три уровня и увеличиваю счетчик, когда обнаруживаю, что у предмета есть дети.
Однако я хочу иметь возможность рекурсивной проверки, пока в массиве нет дочерних элементов.
[
{
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.