2017-06-16 103 views
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"},..... 
+0

可以在每個節點定義兩個屬性,如'children'和'data' – dloeda

回答

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": {} 
     } 
     } 
    } 
}