Javascript 要附加属性子计数的对象的递归数组
我需要递归地遍历一个对象数组,每个对象都有一个属性Javascript 要附加属性子计数的对象的递归数组,javascript,recursion,mapreduce,Javascript,Recursion,Mapreduce,我需要递归地遍历一个对象数组,每个对象都有一个属性标签,需要修改它以包含子对象计数 看看这个例子: const nodes = [{ value: 'World', label: 'World', children: [{ label: 'Europe', value: 'Europe', children: [ { label: 'Albania', value: 'AL' }, {
标签
,需要修改它以包含子对象
计数
看看这个例子:
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'
}
]
}
]
}]
}]
这就是我现在所做的,但它不能正常工作,因为正如上面的预期输出
中所提到的,欧洲
的标签将是欧洲(4)
,而我的版本计算欧洲(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
}, [])
}
您可以采用递归方法,从子级获取计数并更新
标签
这种方法改变了数据
函数更新(节点){
返回节点。减少((计数,节点)=>{
if(节点子节点){
var subcount=更新(node.children);
node.label+=`(${subcount})`;
返回计数+子计数;
}
返回计数+1;
}, 0);
}
const nodes=[{label:'World',label:'World',children:[{label:'Europe',value:'alb',value:'AL'},{label:'BeNeLux',value:'BeNeLux',children:[{label:'NL荷兰',value:'BE'},{label:'luxen',value:'LU LU LU lux'}]}];
更新(节点);
console.log(节点)代码>
。作为控制台包装{max height:100%!important;top:0;}
您可以将子级计数分解为一个单独的递归函数:
const节点=[{
价值观:“世界”,
标签:“世界”,
儿童:[{
标签:“欧洲”,
价值观:“欧洲”,
儿童:[
{
标签:“阿尔巴尼亚”,
值:“AL”
},
{
标签:'比荷卢',
价值:'比荷卢',
儿童:[
{
标签:“荷兰”,
值:“NL”
},
{
标签:“比利时”,
值:“BE”
},
{
标签:“卢森堡”,
值:“LU”
}
]
}
]
}]
}]
常量getChildrenCount=(节点,计数=0)=>{
如果(!node.children){
返回1
}
for(node.children的常量子节点){
计数+=getChildrenCount(子级)
}
返回计数;
}
const GetSortedNodeWithChildrenCountLabel=节点=>{
返回节点
.reduce(函数f(输出,节点){
if(节点子节点){
node.label+=`(${getChildrenCount(node)})`
node.children=node.children
.减少(f,[])
}
输出推送(节点)
返回输出
}, [])
}
console.log(GetSortedNodeWithChildrenCountLabel(nodes))
为什么world只有一个值,而不是四个值?@NinaScholz你是对的,它应该是4个索引。我会尝试递归以获取所有子级的计数,algo是从根开始创建递归函数,该函数将计算该节点的每个子节点的计数,这些节点也将启动该函数来计算子节点,然后将其与父节点相加,从而获得每个节点的完整计数。非变异版本如何?我正在使用React渲染标签,每次渲染都会将子计数添加到标签:Europe(4)
->next renderEurope(4)(4)
->Europe(4)(4)
等。