如何使用父ID将对象添加到嵌套的javascript对象

Ara*_*ras 5 javascript rest json

在我的应用程序中,我基于来自服务器的JSON响应创建一个JavaScript对象,类似于:

{
  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: []
   }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个新节点,例如:

 {name: "grandchild three", id: 113, children:[]}
Run Code Online (Sandbox Code Playgroud)

考虑到这一点,我如何将这个新孙子添加到id为11的父母?请注意,我不知道节点的静态路径,id == 11因此我想知道如何只知道它就可以获得该节点id.

编辑:请注意真实案例中的id不要编码对象的路径.我创建了这个简单的例子来演示我正在处理的数据结构.但我无法在我的实际应用程序中使用其id检索对象的路径.

Nie*_*els 8

看到这个小提琴:http://jsfiddle.net/2Dvws/

它将通过ID找到一个对象.并推动新的孩子.由于Javascript中的每个对象都是引用,因此可以将其作为var返回.

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: []}
    ]
};
Run Code Online (Sandbox Code Playgroud)

将返回找到的元素的函数.将调查所有子元素.

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);
            }
        }
    }
};

var bla = findObjectById(ob, 111);

console.log(bla);
bla.children.push({
        name: "child x",
        id: 1111,
        children: []
});
console.log(ob);
Run Code Online (Sandbox Code Playgroud)

输出是id为111的孩子将有1个id为1111的孩子