gpt4 book ai didi

javascript - 如何通过某个键对数组中的对象值求和?

转载 作者:行者123 更新时间:2023-12-03 00:32:21 24 4
gpt4 key购买 nike

我找不到这个问题的解决方案。

我有数组:

const taxItems = [{
taxCode: '430',
taxAmount: 2,
ItemTaxPercentage: 20,
taxCategory: '2'
},
{
taxCode: '430',
taxAmount: 4,
ItemTaxPercentage: 20,
taxCategory: '2'
},
{
taxCode: '431',
taxAmount: 5,
ItemTaxPercentage: 20,
taxCategory: '2'
},
{
taxCode: '430',
taxAmount: 6,
ItemTaxPercentage: 20,
taxCategory: '2'
}
]

从这个数组中,我想按taxCode 汇总所有对象。我希望得到如下结果:

var results = [{
taxCode: '430',
taxAmount: 12,
ItemTaxPercentage: 20,
taxCategory: '2'
},
{
taxCode: '431',
taxAmount: 5,
ItemTaxPercentage: 20,
taxCategory: '2'
}
]

我尝试使用lodash:

var results =
lodash(taxItems)
.groupBy('taxCode')
.map((objs, key) => ({
'taxCode': key,
'taxAmount': lodash.sumBy(objs, 'taxAmount') }))
.value();

但它仅适用于键值对。我将失去对象的原始结构。

解决我的问题的正确方法是什么?

最佳答案

将每组的第一个对象扩展到结果对象中,以获得重复属性:

const taxItems = [{"taxCode":"430","taxAmount":2,"ItemTaxPercentage":20,"taxCategory":"2"},{"taxCode":"430","taxAmount":4,"ItemTaxPercentage":20,"taxCategory":"2"},{"taxCode":"431","taxAmount":5,"ItemTaxPercentage":20,"taxCategory":"2"},{"taxCode":"430","taxAmount":6,"ItemTaxPercentage":20,"taxCategory":"2"}];

const results = _(taxItems)
.groupBy('taxCode')
.map((objs, taxCode) => ({
..._.head(objs),
taxCode,
taxAmount: _.sumBy(objs, 'taxAmount') }))
.value();

console.log(results);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

关于javascript - 如何通过某个键对数组中的对象值求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53804425/

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