所以,我构建了一个像这样的
对象的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"},.....
答案 0 :(得分:2)
所以你需要存储名字和孩子..
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": {}
}
}
}
}