【发布时间】:2019-12-12 09:06:09
【问题描述】:
我需要递归循环一个对象数组,每个对象对象都有一个属性label,需要对其进行修改以包含children计数。
看看这个例子:
const nodes = [{
value: 'World',
label: 'World',
children: [{
label: 'Europe',
value: 'Europe',
children: [
{
label: 'Albania',
value: 'AL'
},
{
label: 'BeNeLux',
value: 'BeNeLux',
children: [
{
label: 'The Netherlands',
value: 'NL'
},
{
label: 'Belgium',
value: 'BE'
},
{
label: 'Luxembourg',
value: 'LU'
}
]
}
]
}]
}]
预期的输出是:
const expectedOutput = [{
value: 'World',
label: 'World (4)',
children: [{
label: 'Europe (4)',
value: 'Europe',
children: [
{
label: 'Albania',
value: 'AL'
},
{
label: 'BeNeLux (3)',
value: 'BeNeLux',
children: [
{
label: 'The Netherlands',
value: 'NL'
},
{
label: 'Belgium',
value: 'BE'
},
{
label: 'Luxembourg',
value: 'LU'
}
]
}
]
}]
}]
这是我现在正在工作的内容,但它无法正常工作,因为正如上面 expectedOutput 中提到的,Europe 的标签将是 Europe (4) 而我的版本计数 Europe (2) 因为它忽略了里面的孩子欧洲。
export const getSortedNodesWithChildrenCountLabel = nodes => {
return nodes
.reduce(function f (output, node) {
if (node?.children) {
node.label += ` (${node.children.length})`
node.children = node.children
.reduce(f, [])
}
output.push(node)
return output
}, [])
}
【问题讨论】:
-
为什么世界只有一个,而不是四个?
-
@NinaScholz 你说得对,确实应该是 4
-
我会尝试递归来获取所有孩子的数量,算法是你从根开始并创建递归函数,它将计算这个节点的每个孩子的数量,这些节点也会触发这个函数计算子节点,然后将其与其父节点相加,以便获得每个节点的完整计数
标签: javascript recursion mapreduce