如何使用父ID将对象添加到嵌套javascript对象 [英] How to add an object to a nested javascript object using a parent id

查看:55
本文介绍了如何使用父ID将对象添加到嵌套javascript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我基于服务器的JSON响应创建一个JavaScript对象,如下所示:

In my application I create a JavaScript object based on a JSON response from the server similar to this:

{
  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: []
   }
  ]
}

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

I create a new node such as:

 {name: "grandchild three", id: 113, children:[]}

考虑到这一点,如何将这个新的孙子添加到其ID为11的父母中?请注意,我不知道使用id == 11到达节点的静态路径,所以我想知道如何仅知道id即可获得该节点.

With this in mind, how can I add this new grandchild to its parent with id 11? Please note that I don’t know the static path to node with id == 11 so I am wondering how I could obtain that node with just knowing it's id.

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

please note the id's in the real case do NOT encode the path to objects. I created this simple example for demonstration of the data structure I am dealing with. But I can not retrieve the path to the object using its id in my real application.

推荐答案

查看此小提琴: http://jsfiddle.net/2Dvws/

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

It will find an object by ID. And push the new child. Since every object within Javascript is a reference, you can return it as an 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: []}
    ]
};

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

The function which will return the found element. Will look into all child elements.

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

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

Output is that child with id 111 will have 1 child with id 1111 ​

这篇关于如何使用父ID将对象添加到嵌套javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆