Javascript 替换对象树中的对象

Javascript 替换对象树中的对象,javascript,Javascript,我需要替换对象树中的一个对象,我尝试了几种方法,但都失败了 let data = [ { "accountId": 2 }, { "accountId": 6, "children": [{ "accountId": 8 }] }, { "accountId": 45 } ]; 在上面的对象数组中,我需要替换(当我知道accoundId时) 到 是否有任何方法/库可以

我需要替换对象树中的一个对象,我尝试了几种方法,但都失败了

let data = [
    {
      "accountId": 2
    }, 
    {
      "accountId": 6,
      "children": [{
        "accountId": 8
      }]
    }, 
    {
      "accountId": 45
    }
];
在上面的对象数组中,我需要替换(当我知道
accoundId
时)


是否有任何方法/库可以做到这一点。

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

var data=[{“accountId”:2},{“accountId”:6,“子项”:[{“accountId”:8},{“accountId”:45}];
var newData={“accountId”:2,“子项”:[{“accountId”:85}]};
数据=(函数upd(数据,n){
返回data.map(e=>{
如果(如儿童){
var o={};
o、 accountId=e.accountId;
o、 儿童=upd(即儿童,n);
返回o;
}
else if(e.accountId==8){
返回n;
}否则返回e;
});
})(数据,新数据);

document.write(''+JSON.stringify(数据,0,2)+'')您可以使用迭代函数来搜索数组项的id和更新

函数makeUpdate(a,u){
返回数组.isArray(a)和&a.some(函数(b,i,bb){
如果(b.accountId==u.accountId){
bb[i]=u;
返回true;
}
返回makeUpdate(b.children,u);
});
}
var data=[{“accountId”:2},{“accountId”:6,“子项”:[{“accountId”:8}],{“accountId”:45}],
update={“accountId”:8,“children”:[{“accountId”:85}]};
makeUpdate(数据,更新);

document.write(''+JSON.stringify(数据,0,4)+'')您如何获得
子项
?一些逻辑或硬编码数据?是的,它表示子帐户(子帐户)api发送的数据对象如下不清楚。您是如何获得值85的?是的,但如果我要替换子帐户数组中的
accountId=8
,则该值无效。
{
  "accountId": 2
}
{
  "accountId": 2,
  "children": [
    {
      "accountId": 85
    }
  ]
}