javascript - 如何根据javascript中的键合并和替换两个数组中的对象?

标签 javascript arrays node.js object

我有两个数组对象(arrayList1、arrayList2)。只是我试图将这两个数组合并到一个数组对象中。 我使用了以下术语。

  • 根据键名类型将两个数组合并为一个数组。
  • arrayList2 的值将覆盖 arrayList1。
  • 我得到了预期的输出,但我担心如何使用高效和性能的方式..

谁能简化我的代码..

注意:

  • 如果使用 Array.reduce 函数而不使用任何插件/库,那就太好了。
  • 我添加了 smaple 输入以供理解。元素顺序将发生变化,两个数组的大小也将发生变化。

const arrayList1 = [
    { type: "A", any: 11, other: "ab", props: "1" },
    { type: "B", any: 22, other: "bc", props: "2" }, // same type
    { type: "C", any: 33, other: "df", props: "3" }
];
 
const arrayList2 = [
    { type: "D", any: 44, other: "aa", props: "11" },
    { type: "B", any: 22, other: "bb", props: "2----2" , x: 10}, // same type
    { type: "E", any: 44, other: "cc", props: "33" }
];

result = arrayList2.reduce(function (arr1, arr2) {
  let isMatchFound = false;
  arr1.forEach(function (list) {
    if (arr2.type == list.type) {
      list = Object.assign(list, arr2);
      isMatchFound = true;
    }
  });
  if (!isMatchFound) {
    arr1.push(arr2);
  }
  return arr1;
}, arrayList1);

console.log('result', JSON.stringify(result));

最佳答案

您还可以使用 .reduce()Object.values() 方法来获得所需的输出:

const arrayList1 = [
    { type: "A", any: 11, other: "ab", props: "1" },
    { type: "B", any: 22, other: "bc", props: "2" }, // same type
    { type: "C", any: 33, other: "df", props: "3" }
];
 
const arrayList2 = [
    { type: "D", any: 44, other: "aa", props: "11" },
    { type: "B", any: 22, other: "bb", props: "2----2" , x: 10}, // same type
    { type: "E", any: 44, other: "cc", props: "33" }
];

const result = Object.values(
   [].concat(arrayList1, arrayList2)
     .reduce((r, c) => (r[c.type] = Object.assign((r[c.type] || {}), c), r), {})
);
                 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何根据javascript中的键合并和替换两个数组中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54321579/

相关文章:

Java:生成自定义元素集

c++ - 这个数组如何合法?

javascript - 计算的可观察量不更新值

javascript - 动态表单验证并禁用提交按钮

c++ - 将文件内容复制到字符串

node.js - Facebook Messenger 机器人永久菜单

node.js - Vorto-Dashboard 不显示设备数据

node.js - Express JS不渲染jade模板

JavaScript - 添加 ID 和类

javascript - 如何在 Chrome 扩展程序中操作新窗口?