我有一些像這樣的數據(簡化):我該如何去「總結」這樣的對象數組?
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
,總結了quantity
和amount
並保持相同的category
和subcategory
(這將是所有相同的同產品的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();
}
當然有更好的辦法嗎?
如果你可以使用箭頭功能,'函數(銷售){回報號碼(sale.quantity); ''成爲'銷售 - >號碼(sale.quantity)''。這有點簡潔。 – Amy
不幸的是,我不能在這個項目中使用ES2015,因爲JavaScript沒有通過任何構建工具運行。 –
是'quantity'和'amount'某種相關的? –