2012-11-02 205 views
1

我有一個JSON樹結構:JSON樹於母公司連桿結構

nodes = 
[ 
{ 
    "name": "user1", 
    "children": [ 
     { 
      "name": "user2" 
     }, 
     { 
      "name": "user3", 
      "children": [ 
       { 
        "name": "user4" 
       } 
      ] 
     }, 
     { 
      "name": "user5" 
     } 
    ] 
} 
] 

,我想轉換到父連桿結構:

[{"name": "user1","parent": "null"}, 
{"name": "user2","parent": "user1"}, 
{"name": "user3","parent": "user1"}, 
{"name": "user4","parent": "user3"}, 
{"name": "user5","parent": "user1"}] 

我試圖穿越樹遞歸但沒有成功訪問父對象:

rebuild(nodes,parentLink); 

function parentlink(key,value) { 
    var obj = { name: value , parent: ??? }; 
    if (key == "name"){ 
     nodes.push(obj); 
    } 
} 

function rebuild(o,func) { 
    for (i in o) { 
     func.apply(this,[i,o[i]]) 
     if (typeof(o[i])=="object") { 
     traverse(o[i],func,nodes); 
     } 
    } 
} 

在開發人員工具中,我可以看到父對象每個孩子,但我不知道如何訪問它們。我應該怎麼做才能將父母添加到每個用戶?

回答

2

我不會說謊,我沒有理會看着你的代碼 - 這是我會怎麼做:

http://jsfiddle.net/J6G2W/1/

function processChildren(item, ret, parent) { 
    for (var i = 0; i < item.length; i++) { 
     var cur = item[i]; 
     var cur_name = cur.name; 
     ret.push({"user": cur_name, "parent": parent}); 
     if ("children" in cur && cur.children.length > 0) { 
      processChildren(cur.children, ret, cur_name); 
     } 
    } 
} 

var all = []; 

processChildren(nodes, all, null); 

console.log(JSON.stringify(all)); 

輸出是:

[{"user":"user1","parent":null},{"user":"user2","parent":"user1"},{"user":"user3","parent":"user1"},{"user":"user4","parent":"user3"},{"user":"user5","parent":"user1"}] 

這似乎是你在找什麼。歡迎您來修改我的代碼什麼的工作更像是你的,我只是想我會分享什麼我會做:)

UPDATE

如果由於某種原因,你想使之更加擴展,你可以自定義哪些鍵是「名」,並且是「孩子」 ......例如:

http://jsfiddle.net/J6G2W/2/

function startProcess(item, ret, key_look, children_look, parent) { 
    function processChildren(item2, ret2, parent2) { 
     for (var i = 0; i < item2.length; i++) { 
      var cur = item2[i]; 
      var cur_name = key_look in cur ? cur[key_look] : null; 

      ret.push({"user": cur_name, "parent": parent2}); 
      if (children_look in cur && cur[children_look].length > 0) { 
       processChildren(cur[children_look], ret, cur_name); 
      } 
     } 
    } 

    processChildren(item, ret, parent); 
} 

var all = []; 

startProcess(nodes, all, "name", "children", null); 

console.log(JSON.stringify(all)); 

注意如何,你只需要指定key_look, children_look AR一次嘗試。內部函數可以訪問這些參數,而只傳遞每個遞歸的重要事情。這可能並不重要,我只是想弄明白:)

+0

謝謝,很好!遞歸傳遞父代是事物。 – graphmeter

+0

@graphmeter沒問題!我做了更多的定製更新,但它可能沒有必要,只是有趣的搞清楚! – Ian

+0

謝謝!不錯的功能,它可能會在稍後的一點:)。 – graphmeter