如何基于javascript中的键合并和替换两个数组中的对象? [英] How to merge and replace objects from two arrays based on a key in javascript?
本文介绍了如何基于javascript中的键合并和替换两个数组中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数组对象(arrayList1,arrayList2).我只是想将这两个数组合并为一个数组对象. 我使用了以下术语.
I have two array object(arrayList1,arrayList2). Just I am trying to merge those two arrays into one array object. The following terms I used.
- 两个基于键名合并为一个数组的数组都是 type .
- arrayList2的值将覆盖arrayList1.
- 我获得了预期的输出,但是我想用高效和高性能的方式来做..
有人可以简化我的代码吗?.
Can someone please simplify my code..
注意:
- 如果使用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()
方法来获得所需的输出:
You may also use .reduce()
and Object.values()
methods to get the desired output:
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中的键合并和替换两个数组中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文