javascript推入嵌套树对象

时间:2012-11-03 11:59:06

标签: javascript json

我尝试使用此SO问题的代码段: How to add an object to a nested javascript object using a parent id

当你尝试在树中进一步插入它时,它会在返回未定义的情况下工作。

我试图解决这个问题,但我错过了一些东西 所以我需要一些帮助。

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)

1 个答案:

答案 0 :(得分: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)