javascript - 替换对象树中的对象

标签 javascript

我需要从对象树中替换一个对象,我尝试了几种方法但我不能

let data = [
    {
      "accountId": 2
    }, 
    {
      "accountId": 6,
      "children": [{
        "accountId": 8
      }]
    }, 
    {
      "accountId": 45
    }
];

在上面的对象数组中,我需要替换(当我知道 accoundId 时)

{
  "accountId": 2
}

{
  "accountId": 2,
  "children": [
    {
      "accountId": 85
    }
  ]
}

有什么方法/库可以做到这一点。

最佳答案

普通 javascript,使用 Array.prototype.map 函数:

var data = [{ "accountId": 2 }, { "accountId": 6, "children": [{ "accountId": 8 }] }, { "accountId": 45 }];

var newData = { "accountId": 2, "children": [{ "accountId": 85 }] };

data = (function upd(data, n) {
    return data.map(e => {
        if (e.children) {
            var o = {};
            o.accountId = e.accountId;
            o.children = upd(e.children, n);
            return o;
        }
        else if (e.accountId == 8) {
            return n;
        } else return e;
    });
})(data, newData);

document.write('<pre>' + JSON.stringify(data, 0, 2) + '</pre>');

关于javascript - 替换对象树中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36200725/

相关文章:

javascript - 在 MathML 渲染中使用命名空间

javascript - 使用 Fabric.js 在初始加载后修改 fabric.Image.fromURL

javascript - 向作用域变量 AngularJS 插入和读取 JSON 数据

javascript - 由于 CORS 问题,通过浏览器的 JS-IPFS http 客户端失败

javascript - 创建自定义文档操作 Alfresco javascript

Javascript:在异步函数中返回一个 promise

javascript - 如何使用 bootstrap-datepicker 沙盒限制 1 个月内的天数选择?

Javascript原型(prototype)继承

javascript - 处理 promise : How to return a list having promises from a for loop?

Javascript 函数在调用时不工作