0

Transaction.ts

export class Transaction {
    id: string;
    category: Category = new Category();
    totalPrice: number;
}

Category .ts

export class Category {
    id: string;
    name: string;
}

I have an array of Transaction as shown below.

id:"1"
category: {id: "1", name: "Plumber"}
totalPrice: 500

id:"2"
category: {id: "1", name: "Plumber"}
totalPrice: 500

id:"3"
category: {id: "2", name: "Electrician"}
totalPrice: 1000

Now I need to group that data as shown below.

enter image description here

I have tried to group it using lodash. But unable to format the way which I need (as shown above). Can I have any support here?

This is what I tried. It just returned individual objects. After that?

let myArray = groupBy(this.data.transactions, (n) => {
      return n.category.name;
    });

Like this (data is different here.Just dummy data)

enter image description here

Update:

 let a = groupBy(this.data.transactions, (n) => {
      return n.category.name;
    }).map((objs, key) => ({
      'name': key,
      'totalPrice': sumBy(objs, 'totalPrice')
    })).value();

Above gives this error:

core.es5.js:1084 ERROR Error: Uncaught (in promise): TypeError: Object(...)(...).map is not a function TypeError: Object(...)(...).map is not a function

Update 2:

  const resultArray = [...reduce(this.data.transactions,(r, { totalPrice, category: { name } }) => {
      const item = r.get(name) || {
        name,
        totalPrice: 0
      };

      item.totalPrice += totalPrice;

      return r.set(name, item);
    }, new Map()).values()];

ERROR:

ERROR Error: Uncaught (in promise): TypeError: Object(...)(...).values(...).slice is not a function TypeError: Object(...)(...).values(...).slice is not a function

Sampath
  • 63,341
  • 64
  • 307
  • 441
  • Possible duplicate of [How to group data in Angular 2 ?](https://stackoverflow.com/questions/37248580/how-to-group-data-in-angular-2) – Ramesh Rajendran Oct 06 '17 at 13:21
  • 1
    Hope I don't need to write `pipe` here. This is just a matter of choosing correct `Lodash` methods. Please remove the duplicate tag. @RameshRajendran – Sampath Oct 06 '17 at 13:28

1 Answers1

1

You need groupBy and sumBy,

var grouped =  _(jsonarray)
    .groupBy('category.name')
    .map((objs, key) => ({
        'name': key,
        'totalPrice': _.sumBy(objs, 'totalPrice') }))
    .value();

DEMO

var jsonarray = [{id:"1",
category: {id: "1", name: "Plumber"},
totalPrice: 500
},
{
id:"2",
category: {id: "1", name: "Plumber"},
totalPrice: 500
},
{
id:"3",
category: {id: "2", name: "Electrician"},
totalPrice: 1000
}];



var grouped =  _(jsonarray)
    .groupBy('category.name')
    .map((objs, key) => ({
        'name': key,
        'totalPrice': _.sumBy(objs, 'totalPrice') }))
    .value();

console.log(grouped);
<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396