我使用lodash模块分组如下:
export class DtoTransactionCategory {
categoryName: String;
totalPrice: number;
}
GROUPBY
import { groupBy} from 'lodash';
let result = groupBy(transactionCategoryList, (c: DtoTransactionCategory) => {
return c.categoryName
});
结果:
所以现在我需要像这样得到上面的数组(即totalPrice
是sum
的{{1}}):
group
你能告诉我如何实现最后一步吗?我在这里使用let myNewArry = [{categoryName:"cat1",totalPrice: 9400},
{categoryName:"cat2",totalPrice: 600}]
。
答案 0 :(得分:1)
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>