2

我尝试使用此 SO 问题中的代码片段: 如何使用父 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)
4

1 回答 1

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)
于 2012-11-04T01:42:15.877 回答