获取与类别对应的对象中的数量



我想把同一只猫的所有quantity加起来。

var  data = [
{ cat: 'EK-1',name:"test",info:"mat", quantity: 3},
{ cat: 'EK-2', name:"test2",info:"nat"quantity: 1}
];

我有一个数组的对象有一些相似的对象。如何添加数量和创建唯一的对象?这是我尝试过的。

var data = [{
cat: 'EK-1',
name: "test",
info: "mat",
quantity: 1
},
{
cat: 'EK-1',
name: "test",
info: "mat",
quantity: 1
},
{
cat: 'EK-1',
name: "test",
info: "mat",
quantity: 1
},
{
cat: 'EK-2',
name: "test2",
info: "nat",
quantity: 1
}
];
const products = Array.from(data.reduce((acc, {
cat,
quantity
}) =>
acc.set(cat, (acc.get(cat) || 0) + quantity),
new Map()
), ([cat, quantity]) => ({
cat,
quantitya
}));
console.log(products);

首先使用reduce对类别键下的数量进行分组和求和,然后使用Object.values丢弃这些键。

var data = [{
cat: 'EK-1',
name: "test",
info: "mat",
quantity: 1
},
{
cat: 'EK-1',
name: "test",
info: "mat",
quantity: 1
},
{
cat: 'EK-1',
name: "test",
info: "mat",
quantity: 1
},
{
cat: 'EK-2',
name: "test2",
info: "nat",
quantity: 1
}];

const result = Object.values(data.reduce((acc, item) => {
if (!acc[item.cat]) {
acc[item.cat] = item;
} else {
acc[item.cat] = { ...item, quantity: item.quantity + acc[item.cat].quantity }
}
return acc;      
}, {}))

console.log(result)

您可以获得完整的对象作为映射的值并增加数量。

const
data = [{ cat: 'EK-1', name: "test", info: "mat", quantity: 1 }, { cat: 'EK-1', name: "test", info: "mat", quantity: 1 }, { cat: 'EK-1', name: "test", info: "mat", quantity: 1 }, { cat: 'EK-2', name: "test2", info: "nat", quantity: 1 }],
products = Array.from(
data
.reduce(
(acc, o) => acc.set(o.cat, { ...o, quantity: (acc.get(o.cat)?.quantity || 0) + o.quantity }),
new Map
)
.values()
);
console.log(products);
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新