我想知道合并2个对象数组itemsA
和itemsB
的最佳方法是什么。合并后的数据应位于mergedList
中。
标准:
source='STAPLE'
项不应在合并数组中重复。name: 'Ball'
项source: 'USER'
可能会存在两次。 itemsA
有6件商品,itemsB
有7件商品,mergedList
应该有11件商品
let itemsA = [
{name: 'Milk', source: 'STAPLE'},
{name: 'Bread', source: 'AD'},
{name: 'Egg', source: 'STAPLE'},
{name: 'Ball', source: 'USER'},
{name: 'Pasta', source: 'STAPLE'},
{name: 'Coke', source: 'AD'}];
let itemsB = [
{name: 'Milk', source: 'USER'},
{name: 'Bread', source: 'AD'},
{name: 'Egg', source: 'STAPLE'},
{name: 'Ball', source: 'USER'},
{name: 'Mango', source: 'USER'},
{name: 'Pasta', source: 'STAPLE'},
{name: 'Coke', source: 'USER'}]
mergedList
应该等于
let mergedList = [
{name: 'Milk', source: 'STAPLE'},
{name: 'Bread', source: 'AD'},
{name: 'Egg', source: 'STAPLE'},
{name: 'Ball', source: 'USER'},
{name: 'Pasta', source: 'STAPLE'},
{name: 'Coke', source: 'AD'}]
{name: 'Milk', source: 'USER'},
{name: 'Bread', source: 'AD'},
{name: 'Ball', source: 'USER'},
{name: 'Mango', source: 'USER'},
{name: 'Coke', source: 'USER'}] ];
答案 0 :(得分:1)
function merge(itemsA, itemsB) {
let merged = [];
itemsA.concat(itemsB).reduce((stapleSet, obj) => (obj.source != "STAPLE") ?
(merged.push(obj), stapleSet) :
(stapleSet.has(obj.name) || merged.push(obj),
stapleSet.add(obj.name), stapleSet), new Set());
return merged;
}
减少连接数组 - 如果对象源是主要的而不在stapleSet
中,则将对象的名称添加到stapleSet
- 设置对象只允许每个条目中的一个 - 然后将对象推送到merged
数组。否则将对象推送到merged
数组。
从函数返回合并的数组。
let itemsA = [
{name: 'Milk', source: 'STAPLE'},
{name: 'Bread', source: 'AD'},
{name: 'Egg', source: 'STAPLE'},
{name: 'Ball', source: 'USER'},
{name: 'Pasta', source: 'STAPLE'},
{name: 'Coke', source: 'AD'}];
let itemsB = [
{name: 'Milk', source: 'USER'},
{name: 'Bread', source: 'AD'},
{name: 'Egg', source: 'STAPLE'},
{name: 'Ball', source: 'USER'},
{name: 'Mango', source: 'USER'},
{name: 'Pasta', source: 'STAPLE'},
{name: 'Coke', source: 'USER'}];
function merge(itemsA, itemsB) {
let merged = [];
itemsA.concat(itemsB).reduce((stapleSet, obj) => (obj.source != "STAPLE") ?
(merged.push(obj), stapleSet) :
(stapleSet.has(obj.name) || merged.push(obj),
stapleSet.add(obj.name), stapleSet), new Set());
return merged;
}
console.log( merge(itemsA, itemsB) );

修改:OP的其他格式
function merge(itemsA, itemsB) {
let merged = [];
itemsA.concat(itemsB).reduce((stapleSet, obj) => {
if (obj.source != "STAPLE") {
merged.push(obj);
return stapleSet;
} else {
if (stapleSet.has(obj.name)) {
return stapleSet;
} else {
merged.push(obj);
stapleSet.add(obj.name);
return stapleSet;
}
}
}, new Set());
return merged;
}