我正在尝试获取密钥中的最大对象数,在这种情况下是“child”。对于每个对象和子对象,我想达到每个对象和子对象所达到的水平。希望你能理解这个问题。这对我来说很重要
例如:
[{
name:"Node Parent 1 Level 0",
childs:[{
name:"Sub Node 1 Level 1",
childs:[{
name:"Sub Node 1 Level 2"
}]
},{
name:"Sub Node 2"
},{
name:"Sub Node 3"
}]
},{
name:"Node Parent 2 Level 0",
childs:[{
name:"Sub Node 1 Level 1",
childs:[{
name:"Sub Node 1 Level 2"
},{
name:"Sub Node 2 Level 2",
childs:[{
name:"Sub Node 1 Level 3"
},{
name:"Sub Node 2 Level 3",
childs:[{
name:"Sub Node 1 Level 4"
},{
name:"Sub Node 2 Level 4"
}]
}]
}]
},{
name:"Sub Node 2 Level 1",
childs:[{
name:"Sub Node 1 Level 2"
},{
name:"Sub Node 2 Level 2",
childs:[{
name:"Sub Node 1 Level 3"
},{
name:"Sub Node 2 Level 3"
}]
}]
}]
}]
答案 0 :(得分:0)
基于您的评论,这样的事情:
版本2.0 代码可能需要重构,但我认为这是您正在寻找的解决方案:
var obj1= [{/* Based on updated sample code */ }];
function getCount(obj2){
var res = obj2.reduce(function(res,node){ return res += Object.keys(node).reduce(
function(res,value){
if (value==="childs"){
res +=2 + getCount(node[value]);
res -= obj2.filter(function(n){ return Object.keys(n).some(function(propName){ return propName ==="childs"; }); }).length;
}
return res;
},0 );
},0);
return res;
}
console.log('Show Levels')
for(var i=0;i<obj1.length;i++){
console.log( 'Object =>',obj1[i].name, " level= ", getCount([obj1[i]]));
}
版本1.0
var parent1= [{
name:"Node Parent 2",
childs:[{
name:"Sub Node 2"
},
{
name:"Sub Node 3",
childs:[{
name:"Sub Sub Node 1"
},{
name:"Sub Sub Node 2",
childs:[{
name:"Sub Sub Sub Node 1"
},{
name:"Sub Sub Sub Node 2"
}]
}]
}]
}];
function getCount(obj2){
var res = obj2.reduce(function(res,node){ return res += Object.keys(node).reduce(
function(res,value){
if (value==="childs"){ res +=1 + getCount(node[value]); }
return res;
},0 );
},0);
return res;
}
console.log("final count", getCount(parent1));