【问题标题】:Merge two arrays without override [duplicate]合并两个数组而不覆盖[重复]
【发布时间】:2021-07-01 12:35:35
【问题描述】:

我有两个要合并的数组,但我似乎无法弄清楚如何不覆盖具有相同值/id/数字的属性。

我现在拥有的:

第一个数组

0: {id: 1, title: "Button", type: "Controls & Inputs"}
1: {id: 2, title: "Switch", type: "Selection Controls"}
2: {id: 3, title: "Tags", type: "Controls & Inputs"}
3: {id: 4, title: "Checkbox", type: "Selection Controls"}
4: {id: 5, title: "Toast", type: "Notifications & Alerts"}

第二个数组

0: {id: 1, title: "Colors", type: "Design"}
1: {id: 2, title: "Typography", type: "Design"}

预期输出:

0: {id: 1, title: "Button", type: "Controls & Inputs"}
1: {id: 2, title: "Switch", type: "Selection Controls"}
2: {id: 3, title: "Tags", type: "Controls & Inputs"}
3: {id: 4, title: "Checkbox", type: "Selection Controls"}
4: {id: 5, title: "Toast", type: "Notifications & Alerts"}
5: {id: 1, title: "Colors", type: "Design"}
6: {id: 2, title: "Typography", type: "Design"}

【问题讨论】:

  • 您已将这些“对象”称为“对象”,但您对它们的渲染看起来像是专门的 array 对象。这是真的吗?
  • 否 :( 我只需要将第二个对象值添加到第一个对象值检查预期输出...第二个对象属性添加到第一个对象属性为 5,6
  • @T.J.Crowder 是的,没错
  • 所以,基本上,你只想concat他们? const res = arr1.concat(arr2);

标签: javascript arrays merge


【解决方案1】:

这些看起来像数组,而不是对象。如果是这样,您可以使用concat 方法将它们组合起来,如下所示:

let result = [].concat(first, second);

或通过使用扩展运算符,如下所示:

let result = [...first, ...second];

【讨论】:

  • 这成功了!谢谢,我会在 8 分钟内给这个答案打分
  • 好答案。仅供参考,.concat() 调用不需要无用的空数组(以及额外的对象创建)。就做first.concat(second)
  • 如果你愿意,你也可以Array.prototype.concat(first, second)
猜你喜欢
  • 2014-01-02
  • 1970-01-01
  • 2023-01-19
  • 2013-07-11
  • 2022-11-02
  • 2013-12-27
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
相关资源
最近更新 更多