我需要使用objects
语法合并两个es6
数组,并且没有重复项。在我的任务中,对象中没有几个其他按键。
但是我认为这不是问题。在array2
中,array1
内始终包含对象
这是数组
array1 = [
{name: 'one', count: 0},
{name: 'two', count: 0},
{name: 'three', count: 0},
{name: 'four', count: 0}
]
array2 = [
{name: 'two', count: 4},
{name: 'four', count: 2}
]
我需要这个:
array3 = [
{name: 'one', count: 0},
{name: 'two', count: 4},
{name: 'three', count: 0},
{name: 'four', count: 2}
]
答案 0 :(得分:1)
const array1 = [
{name: 'one', count: 0},
{name: 'two', count: 0},
{name: 'three', count: 0},
{name: 'four', count: 0}
]
const array2 = [
{name: 'two', count: 4},
{name: 'four', count: 2}
]
const result = array1.map(a => {
const b = array2.find(b => b.name === a.name);
if (b) {
return {name: a.name, count: a.count + b.count}
}
return a;
});
console.log(result);
答案 1 :(得分:0)
let all = array1.concat(array2)
//avoid dupplicates by key
let map = all.reduce((acc,item)=>{acc[item.name] = item; return acc;},{});
//convert map back to array
let array3 = Object.values(map)
console.log(array3);
//
[ { name: 'one', count: 0 },
{ name: 'two', count: 4 },
{ name: 'three', count: 0 },
{ name: 'four', count: 2 } ]
答案 2 :(得分:0)
map
可用于在数组的每个元素上调用函数。与使用find
的版本的主要区别在于它将遍历array2
的所有元素,因此,如果数组中有2个元素带有name: 'two'
的元素,则这两个元素都会使计数。使用find
,只有找到的拳头会添加。
const array1 = [
{name: 'one', count: 0},
{name: 'two', count: 0},
{name: 'three', count: 0},
{name: 'four', count: 0}
],
array2 = [
{name: 'two', count: 4},
{name: 'four', count: 2}
];
const array3 = array1.map(obj => {
let _count = obj.count;
array2.forEach(obj2 => {
if(obj2.name === obj.name){
_count += obj2.count;
}
});
return { name: obj.name, count: _count };
});
console.log(array3);
编辑:根据@HMR建议修改(感谢指出我的错误)+在array2上使用了forEach
,因为我不使用任何返回的数组