我下面有一个对象。我需要编写一个迭代每个孩子的for循环 并显示ID。
我使用了下划线库,但未找到解决方案
*[
{
Id:1,
Name:"Test",
children:[
{
Id:11,
Name:"Test",
children:[
{
Id:113,
Name:"Test",
children:[
]
},
{
Id:114,
Name:"Test",
children:[
]
}
]
},
{
Id:12,
Name:"Test",
children:[
]
},
{
Id:13,
Name:"Test",
children:[
{
Id:115,
Name:"Test",
children:[
{
Id:1111,
Name:"Test",
children:[
]
}
]
}
]
},
{
Id:14,
Name:"Test",
children:[
]
}
]
} {
Id:2,
Name:"Test",
children:[
]
}
]*
答案 0 :(得分:4)
你可以这样做:
var items= [
{
Id:1,
Name:"Test",
children:[
{
Id:11,
Name:"Test",
children:[
{
Id:113,
Name:"Test",
children:[
]
},
{
Id:114,
Name:"Test",
children:[
]
}
]
},
{
Id:12,
Name:"Test",
children:[
]
},
{
Id:13,
Name:"Test",
children:[
{
Id:115,
Name:"Test",
children:[
{
Id:1111,
Name:"Test",
children:[
]
}
]
}
]
},
{
Id:14,
Name:"Test",
children:[
]
}
]
}, {
Id:2,
Name:"Test",
children:[
]
}
];
displayIds(items);
function displayIds(datas) {
datas.forEach(function(data) {
console.log(data.Id);
if (data.children) {
displayIds(data.children);
}
});
}

答案 1 :(得分:1)
var data = [
{
Id:1,
Name:"Test",
children:[
{
Id:11,
Name:"Test",
children:[
{
Id:113,
Name:"Test",
children:[
]
},
{
Id:114,
Name:"Test",
children:[
]
}
]
},
{
Id:12,
Name:"Test",
children:[
]
},
{
Id:13,
Name:"Test",
children:[
{
Id:115,
Name:"Test",
children:[
{
Id:1111,
Name:"Test",
children:[
]
}
]
}
]
},
{
Id:14,
Name:"Test",
children:[
]
}
]
},
{
Id:2,
Name:"Test",
children:[
]
}
];
showId(data);
function showId(data){
for(var i = 0; i < data.length; i++){
console.log(data[i].Id);
if(data[i].children.length > 0){
showId(data[i].children);
}
}
}
&#13;
答案 2 :(得分:0)
您可以像
一样使用递归
var obj = [
{
Id:1,
Name:"Test",
children:[
{
Id:11,
Name:"Test",
children:[
{
Id:113,
Name:"Test",
children:[
]
},
{
Id:114,
Name:"Test",
children:[
]
}
]
},
{
Id:12,
Name:"Test",
children:[
]
},
{
Id:13,
Name:"Test",
children:[
{
Id:115,
Name:"Test",
children:[
{
Id:1111,
Name:"Test",
children:[
]
}
]
}
]
},
{
Id:14,
Name:"Test",
children:[
]
}
]
}, {
Id:2,
Name:"Test",
children:[
]
}
]
function showIds(obj, i=0) {
if(!obj[i]) return
console.log(obj[i].Id);
showIds(obj, i+1)
if(obj[i].children) showIds(obj[i].children);
}
showIds(obj)