[英]recursive javascript function to return detail
所以,我建立了一个JavaScript对象数组
var menu = [
{id:1 , parent:0 , name: 'home'},
{id:2 , parent:0 , name: 'about'},
{id:3 , parent:0 , name: 'products'},
{id:4 , parent:3 , name: 'latest products'},
{id:5 , parent:0 , name: 'news'},
{id:6 , parent:0 , name: 'contacts'},
{id:7 , parent:3 , name: 'archive products'},
{id:8 , parent:5 , name: 'arch news'},
{id:9 , parent:7 , name: 'search archive'}
];
并且我构建了一个递归函数来从该数组中生成一棵树,如下所示:
function makeTree(menu,parent){
var node ={};
menu.filter(function (c) {
return c.parent ===parent
})
.forEach(function(c) {
node[c.id] = makeTree(menu,c.id)
return
});
return (node)
}
console.log(JSON.stringify(makeTree(menu,0),null,3));
该函数可以正常工作,并按预期返回此结果:
{
"1": {},
"2": {},
"3": {
"4": {},
"7": {
"9": {}
}
},
"5": {
"8": {}
},
"6": {}
}
现在,这是我的问题:
如您所见,返回的对象只有id,我该如何在返回中也包含名称,如下所示:
{
"1": {name:"home"},
"2": {name:"about"},.....
所以您需要同时存储名字和孩子。
function makeTree(menu,parent){
var node = {name:menu.name,children:{}};
menu.filter(function (c) {
return c.parent ===parent
})
.forEach(function(c) {
node.children[c.id] = {
name: c.name,
children: makeTree(menu,c.id)
}
return
});
return (node)
}
会给你这个
{
"children": {
"1": {
"name": "home",
"children": {
"children": {}
}
},
"2": {
"name": "about",
"children": {
"children": {}
}
},
"3": {
"name": "products",
"children": {
"children": {
"4": {
"name": "latest products",
"children": {
"children": {}
}
},
"7": {
"name": "archive products",
"children": {
"children": {
"9": {
"name": "search archive",
"children": {
"children": {}
}
}
}
}
}
}
}
},
"5": {
"name": "news",
"children": {
"children": {
"8": {
"name": "arch news",
"children": {
"children": {}
}
}
}
}
},
"6": {
"name": "contacts",
"children": {
"children": {}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.