在下面的阵列,我要通过组item
和reason
,然后计算出总的quantity
:
item_movements = [
{
item: "Apple",
reason: 1,
quantity: 5
},
{
item: "Banana",
reason: 2,
quantity: 10
},
{
item: "Apple",
reason: 1,
quantity: 5
},
{
item: "Banana",
reason: 1,
quantity: 8
},
{
item: "Apple",
reason: 2,
quantity: 3
},
{
item: "Banana",
reason: 1,
quantity: 8
}
];
我想要达到的结果是:
item_totals = [
{
item: "Apple",
1: 10,
2: 3
},
{
item: "Banana",
1: 16,
2: 10
}
];
我可以item
使用Loadash进行分组,如下所示:
({
itemMovementbyItem() {
var result = _(this.item_movements)
.groupBy(x => x.item)
.map((value, key) => ({
item: key,
item_movements: value
}))
.value()
return result
}
})
但是我很难再分组了reason
。
按分组后,您可以直接汇总属性'item'
。
function itemMovementbyItem(array) {
return _(array)
.groupBy('item')
.map(group => ({
item: group[0].item,
1: _.sumBy(group, o => o.reason === 1 ? o.quantity : 0),
2: _.sumBy(group, o => o.reason === 2 ? o.quantity : 0)
}))
.value();
}
var item_movements = [{ item: "Apple", reason: 1, quantity: 5 }, { item: "Banana", reason: 2, quantity: 10 }, { item: "Apple", reason: 1, quantity: 5 }, { item: "Banana", reason: 1, quantity: 8 }, { item: "Apple", reason: 2, quantity: 3 }, { item: "Banana", reason: 1, quantity: 8 }];
console.log(itemMovementbyItem(item_movements));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句