有没有一种简单的方法可以使用javascript省略号或类似的方法来合并对象数组?

问题描述 投票:0回答:1

let arr = [
  {id: 1, data: {foo: "bar 1"}},
  {id: 2, data: {foo: "bar 2"}}
];

//In case the ID does not exist just add as a new element on the array
arr = [...arr, {id: 3, data: {foo: "bar 3"}}]
console.log(arr);

//In case the ID exists, replace the data object with the new array provided
arr = [...arr, {id: 2, data: {foo: "new data object"}}]
console.log(arr);

//Expected output:
[
  {id: 1, data: {foo: "bar 1"}},
  {id: 2, data: {foo: "new data object"}},
  {id: 3, data: {foo: "bar 3"}}
]

正如您在下面的示例中看到的,即使 ID 相同,您也只能添加新元素。

是否有一种方法可以提供一个对象,在存在相同 ID 的情况下替换该对象,但如果找不到 ID,则将其作为新元素添加到数组中?

我知道我可以使用

arr.find(i => i.id == newObject.id)
检查该行是否存在并添加为新行或根据结果进行替换,但我想知道是否有一个单行解决方案

javascript arrays angular multidimensional-array spread-syntax
1个回答
0
投票

let arr = [
  { id: 1, data: { foo: "bar 1" } },
  { id: 2, data: { foo: "bar 2" } }
];

let newObj = { id: 2, data: { foo: "new value1" } };
arr = arr.filter((obj) => obj.id !== newObj.id).concat(newObj);
console.log(JSON.stringify(arr));


newObj = { id: 3, data: { foo: "new value2" } };
arr = arr.filter((obj) => obj.id !== newObj.id).concat(newObj);
console.log(JSON.stringify(arr));

© www.soinside.com 2019 - 2024. All rights reserved.