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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12899609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:22:29  来源:igfitidea点击:

How to add an object to a nested javascript object using a parent id

javascriptjsonrest

提问by Aras

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

在我的应用程序中,我基于来自服务器的 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: []
   }
  ]
}

I create a new node such as:

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

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

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 == 11so I am wondering how I could obtain that node with just knowing it's id.

考虑到这一点,我如何将这个新的孙子添加到其 ID 为 11 的父级?请注意,我不知道节点的静态路径,id == 11所以我想知道如何仅知道它是id.

Edit: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.

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

回答by Niels

See this fiddle: http://jsfiddle.net/2Dvws/

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

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.

它将通过 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: []}
    ]
};

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

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

输出是 ID 为 111 的孩子将有一个 ID 为 1111 的孩子吗?

回答by seaotternerd

Niels' answer is a good start, but doesn't fully traverse the tree (e.g. it will break if the node you're looking for is the child of the second child of the root). Also it breaks if the root is the id you're looking for. Here are my refinements:

Niels 的回答是一个好的开始,但并没有完全遍历树(例如,如果您要查找的节点是根的第二个孩子的孩子,它将中断)。如果根是您要查找的 id,它也会中断。以下是我的改进:

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

回答by Bergi

I assume the id consists of the parent-id plus the index (1 to 9) in the children array? Then you can go like that:

我假设 id 由父 ID 加上子数组中的索引(1 到 9)组成?然后你可以这样:

var rootobj = {…};
var newnode = {name: "grandchild three", id: 113, children:[]};

var id = ""+newnode.id;
var cur = [rootobj];
for (var i=0; i<id.length-i; i++)
    cur = cur[id.charAt(i)-1].children;
cur[id.charAt(i)-1] = newnode;

回答by Austin Brunkhorst

How about this.

这个怎么样。

for(var a = 0; a < object.length; a++) {
    for(var b = 0; b < obj.children.length; b++) {
        if(object[a].children[b].id == 11) {
           object[a].children[b].children.push({
                name: "grandchild three", 
                id: 113, 
                children: []
            });
        }
    }
}