我有一些像这样的数据(简化):
sales: [
{
'quantity': 20,
'amount': 40,
'product': {
'id': 1
'category': 'Chemical',
'subcategory': 'Herbicide'
}
},
{
'quantity': 10,
'amount': 70,
'product': {
'id': 1
'category': 'Chemical',
'subcategory': 'Herbicide'
}
},
{
'quantity': 30,
'amount': 60,
'product': {
'id': 2
'category': 'Seed',
'subcategory': 'Corn'
}
}
]
我想按product.id
对数据进行分组,并对数量
和金额
求和,并保持相同的类别
和 子类别
(对于所有相同的产品 ID 都是相同的)
所以基本上我希望我的数据看起来像这样:
filteredSum: [
{
'quantity': 30,
'amount': 110,
'product': {
'category': 'Chemical',
'subcategory': 'Herbicide'
}
},
{
'quantity': 30,
'amount': 60,
'product': {
'category': 'Seed',
'subcategory': 'Corn'
}
}
]
我正在使用 Lodash,这就是我想到的,但有人告诉我有一种更简洁的方法可以做到这一点?
filteredSum: function () {
return _(this.sales).groupBy('product.id').map(function (sales) {
return {
'quantity': _.sumBy(sales, function(sale) { return Number(sale.quantity); }).toFixed(2),
'amount': _.sumBy(sales, function(sale) { return Number(sale.amount); }),
'product': {
'category': _.head(sales).product.category,
'subcategory': _.head(sales).product.subcategory
}
}
}).value();
}
肯定有更好的方法吗?
最佳答案
最简单的方法是使用一个以 productId
作为主键的对象。然后只需使用 reduce
来迭代数组。如果当前产品的 productId
已存在,只需将其值与前一个值相加,否则将其添加到对象中。
const data = [
{
'quantity': 20,
'amount': 40,
'product': {
'id': 1,
'category': 'Chemical',
'subcategory': 'Herbicide'
}
},
{
'quantity': 10,
'amount': 70,
'product': {
'id': 1,
'category': 'Chemical',
'subcategory': 'Herbicide'
}
},
{
'quantity': 30,
'amount': 60,
'product': {
'id': 2,
'category': 'Seed',
'subcategory': 'Corn'
}
}
];
const result = data.reduce((acc, curr) => {
if (acc[curr.product.id]) {
acc[curr.product.id].quantity += curr.quantity;
acc[curr.product.id].amount += curr.amount;
} else {
acc[curr.product.id] = curr;
}
return acc;
}, {});
const formatedResult = Object.keys(result).map(entry => {
return result[entry];
});
console.log(formatedResult);
关于javascript - 我该如何处理 "summarizing"这样的对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45284979/