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.
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)
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