2017-10-06 2 views
0

J'ai regroupé en utilisant le module lodash comme ci-dessous:groupBy avec le module Lodash

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

groupBy

import { groupBy} from 'lodash'; 

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

Résultat:

enter image description here

Alors maintenant Je dois obtenir le tableau ci-dessus comme ceci (c.-à-d. totalPrice est le sum du group):

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

Pouvez-vous me dire comment réaliser la dernière étape? J'utilise Lodash modules ici.

Répondre

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>

+0

a finalement obtenu un solution.Thank vous :) – Sampath