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

标签 javascript json rest

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

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

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

考虑到这一点,我如何将这个新的孙子添加到其 ID 为 11 的父级?请注意,我不知道带有 id == 11 的节点的静态路径,所以我想知道如何在知道它是 id 的情况下获取该节点。

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

最佳答案

请参阅此 fiddle :http://jsfiddle.net/2Dvws/

它将通过 ID 找到一个对象。并插入新的 child 。由于 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: []}
    ]
};

返回找到的元素的函数。将查看所有子元素。

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 的 child 将有 1 个 id 为 1111 的 child

关于javascript - 如何使用父 id 将对象添加到嵌套的 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12899609/

相关文章:

循环内的Javascript addEventListener

javascript - jQuery sortable ('disable' ) from start event 不完全像预期的那样工作

JavaScript - 直接在多行字符串中循环遍历数组并包含值

python - 将 CSV 转换为 GeoJSON 时如何删除不需要的双引号

azure - 使用 REST 将数据发送到 Azure IoT 中心

javascript - 未捕获的类型错误 : Cannot read property 'length' of null at rating. js:4

json - Zend 框架 1.9.2+ Zend_Rest_Route 示例

json - 从另一个 JSON 对象中提取内部 JSON 对象

java - Spring Boot Rest 中没有内容

javascript - (原因 : CORS header ‘Access-Control-Allow-Origin’ missing)