如何覆盖JavaScript中的嵌套数组对象

时间:2019-03-25 07:46:16

标签: javascript jquery arrays object

我想知道如何合并和覆盖javascript中嵌套数组中已经存在的对象值。

如下所示,我需要将other_obj合并到id =“ zen”的obj,如果属性存在则覆盖,否则覆盖

var obj =[
{id:"abc", 
amount: "100", 
fee: "5.5"},
{id:"xyz", 
amount: "1000", 
fee: "5.5"},
{id:"zen", 
amount: "500", 
fee: "5.5"}]

var other_obj = {
amount: 600,
name: "new"
}


Expected Output: 
{
id:"zen",
amount: 600,
fee: "5.5",
name: new
}

1 个答案:

答案 0 :(得分:0)

使用...传播语法:

var obj = [{
    id: "abc",
    amount: "100",
    fee: "5.5"
  },
  {
    id: "xyz",
    amount: "1000",
    fee: "5.5"
  },
  {
    id: "zen",
    amount: "500",
    fee: "5.5"
  }
];

var other_obj = {
  amount: 600,
  name: "new"
};

var test = {};
obj.forEach(e => test = {...test, ...e});
test = {...test, ...other_obj};
console.log(test);