合并对象并在JavaScript中求和一个属性
假设我们有两个对象数组,其中包含有关公司某些产品的信息-
const first = [{
id: "57e7a1cd6a3f3669dc03db58",
quantity:3
},
{
id: "57e77b06e0566d496b51fed5",
quantity:3
},
{
id: "57e7a1cd6a3f3669dc03db58",
quantity:3
},
{
id: "57e77b06e0566d496b51fed5",
quantity:3
}
];
const second = [
{
id: "57e7a1cd6a3f3669dc03db58",
quantity:6
},
{
id: "57e77b06e0566d496b51fed5",
quantity:6
}
];
现在,我们需要编写一个合并两个数组的函数,以使具有相同ID的对象不会出现重复的外观,此外,对象重复ID的数量属性将加在一起。
因此,让我们为该函数编写代码-
示例
const first = [{
id: "57e7a1cd6a3f3669dc03db58",
quantity:3
},
{
id: "57e77b06e0566d496b51fed5",
quantity:3
},
{
id: "57e7a1cd6a3f3669dc03db58",
quantity:3
},
{
id: "57e77b06e0566d496b51fed5",
quantity:3
}
];
const second = [
{
id: "57e7a1cd6a3f3669dc03db58",
quantity:6
},
{
id: "57e77b06e0566d496b51fed5",
quantity:6
}
];
const mergeArray = (first, second) => {
return [...first, ...second].reduce((acc, val, i, arr) => {
const { id, quantity } = val;
const ind = acc.findIndex(el => el.id === id);
if(ind !== -1){
acc[ind].quantity += quantity;
}else{
acc.push({
id,
quantity
});
}
return acc;
}, []);
}
console.log(mergeArray(first, second));
输出结果
控制台中的输出将为-
[{ id: '57e7a1cd6a3f3669dc03db58', quantity: 12 },
{ id: '57e77b06e0566d496b51fed5', quantity: 12 }
]
以上是 合并对象并在JavaScript中求和一个属性 的全部内容, 来源链接: utcz.com/z/350184.html