gpt4 book ai didi

javascript - groupBy 与 Lodash 模块

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

我使用 lodash 模块进行分组,如下所示:

export class DtoTransactionCategory {
categoryName: String;
totalPrice: number;
}

groupBy

import { groupBy} from 'lodash';

let result = groupBy(transactionCategoryList, (c: DtoTransactionCategory) => {
return c.categoryName
});

结果:

enter image description here

所以现在我需要像这样获取上面的数组(即totalPricegroupsum):

let myNewArry = [{categoryName:"cat1",totalPrice: 9400},
{categoryName:"cat2",totalPrice: 600}]

你能告诉我如何实现最后一步吗?我在这里使用 Lodash 模块

最佳答案

let result = {
cat1: [{totalPrice: 2}, {totalPrice: 3}],
cat2: [{totalPrice: 2}, {totalPrice: 5}]
}
const totals = _.map(result, (val, key) => ({categoryName: key, totalPrice: _.sumBy(val, 'totalPrice')}))

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

关于javascript - groupBy 与 Lodash 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46611526/

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