如何基于javascript中的键合并和替换两个数组中的对象?

RSK*_*KMR 5 javascript arrays object node.js

我有两个数组对象(arrayList1,arrayList2)。我只是想将这两个数组合并为一个数组对象。我使用了以下术语。

  • 两个数组都合并为一个基于key-name的数组,类型type
  • 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));
Run Code Online (Sandbox Code Playgroud)

Moh*_*man 2

您还可以使用.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);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)