RSK*_*KMR 5 javascript arrays object node.js
我有两个数组对象(arrayList1,arrayList2)。我只是想将这两个数组合并为一个数组对象。我使用了以下术语。
有人可以简化我的代码吗..
注意 :
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)
您还可以使用.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)