0
所以,我建對象的JavaScript數組這樣遞歸的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"},.....
可以在每個節點定義兩個屬性,如'children'和'data' – dloeda