gpt4 book ai didi

javascript - 如何使用 Lodash 按多个键分组并将其值汇总到对象数组中?

转载 作者:行者123 更新时间:2023-12-01 03:02:13 30 4
gpt4 key购买 nike

在下面的数组中,我想按 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>

关于javascript - 如何使用 Lodash 按多个键分组并将其值汇总到对象数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60352505/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com