javascript - 如何在数组中组合具有相同值的对象?
问题描述
如何合并具有相同值的对象数组?我有订单数组,可能有相同的产品。如果是这样,我想合并它们并添加数量。
var orders = [
{
product: "chair",
quantity: 5,
price: 900,
},
{
product: "chair",
quantity: 2,
price: 900,
},
]
预期输出:
orders = [
{
product: "chair",
quantity: 7,
price: 900,
}
]
目标:按产品对对象数组进行分组并添加数量。
解决方案
这是实现这一目标的一种有效方法:
var orders = [
{
product: "chair",
quantity: 5,
price: 900,
},
{
product: "chair",
quantity: 2,
price: 900,
},
];
const resultTest = {};
const result = [];
orders.forEach((item) => {
if (resultTest[item.product]) {
const index = resultTest[item.product] -1;
const foundItem = result[index];
const newValue = {
...foundItem,
quantity: foundItem.quantity + item.quantity,
};
result[index] = newValue;
} else {
resultTest[item.product] = result.length + 1;
result.push(item);
}
});
console.log(result);