groupBy与Lodash模块

时间:2017-10-06 18:02:59

标签: javascript angular typescript lodash ionic3

我使用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

所以现在我需要像这样得到上面的数组(即totalPricesum的{​​{1}}):

group

你能告诉我如何实现最后一步吗?我在这里使用let myNewArry = [{categoryName:"cat1",totalPrice: 9400}, {categoryName:"cat2",totalPrice: 600}]

1 个答案:

答案 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>