2012-11-03 93 views
2

我曾嘗試使用一個代碼片段來自這太問題: How to add an object to a nested javascript object using a parent id的JavaScript推到嵌套樹對象

,當你試圖進一步向下插入它爲未定義返回尼特工作的樹。

我試圖解決這個問題,但我錯過了一些東西 所以我需要一些幫助。

http://jsfiddle.net/murray_3/EbJ85/4/

繼承人的代碼:

var ob = { 
    name: "root", 
    id: 1, 
    children: [ 
     { 
      name: "child one", 
      id: 11, 
      children: [ 
      { 
       name: "grand child 1", 
       id: 111, 
       children: [] 
      }, 
      { 
       name: "grand child 2", 
       id: 112, 
       children: [] 
      } 
     ]}, 
     { 
      name: "child two", 
      id: 12, 
      children: [] 
     } 
    ] 
}; 

function findObjectById(root, id) { 
    if (root.children) { 
     for (var k in root.children) { 
      if (root.children[k].id == id) { 
       return root.children[k]; 
     } 
     else if (root.children.length) { 
      return findObjectById(root.children[k], id); 
      } 
     } 
    } 
}; 



function findObjectByLabel(obj, id) { 
    for (i in obj.children) { 
     if(obj.children[i].id === id) { 
      document.write(obj.children[i].id); 
      l= obj.children[i].children.length +1 
      return obj.children[i]; 
     } 
     else { 
      findObjectByLabel(obj.children[i], id); 
      } 
     } 
}; 




function traverse(o,spc) { 
    for (i in o) { 
     if(i == "name"|| i == "id") { 
      document.write(spc + i + " : "+o[i]+"<br>"); 
     }   
     if (typeof(o[i])=="object") { 
      //going on step down in the object tree!! 
      ss = spc+"_" 
      traverse(o[i],ss); 
     } 
    } 
} 


var s ="" 
traverse(ob,s) 
var boo = findObjectByLabel(ob,111) 
var l = boo.children.length 
document.write(typeof(boo)) 
document.write("<br>"+"boo kids l= " +l+"<br>") 
//var boo = findObjectByLabel(ob,111) 
boo.children.push({ 
    name: "child x", 
    id: 11111, 
    children: [] 
}); 
var ll = boo.children.length 
document.write("<br>"+"boo kids l= " +ll+"<br>") 
var s ="" 
traverse(ob,s) 
+0

從我的手機發送的,對不起格式化 – murray3

回答

0

我創造了這個功能,它做什麼,我想:

function testpush(o,idd,tt,tid) { 
    for(var a = 0; a < o.children.length; a++) { 
    if(o.children[a].id == idd) { 
     o.children[a].children.push({ 
      name: tt, 
      id: tid, 
      children: [] 
     }); 
    } 
    else { 
     testp(o.children[a],idd,tt,tid); 
     } 
    } 
}; 

testp(ob,12,"test 121",121) 
testp(ob,121,"test 1211",1211) 
+0

你應該接受你自己答案也是(只要他們是唯一的/最好的) – Bergi