I need to group the array with a nested value type.Id. How to change the current groupby function to achieve this. Current function will group using the productName or Price. Need to group using a nested value type.id Any help would be greatly appreciated!
Group by function
static groupBy<T>(data: T[], key: string): T[] {
return <T[]>data.reduce((a, b) => {
(a[b[key]] = a[b[key]] || []).push(x);
return <T[]>a;
}, {});
}
sample value:
var sales = [
{
"productName": "AAA",
"type": {
"id": 1,
"name": "Soap"
},
"price": 90
},
{
"productName": "BBB",
"type": {
"id": 1,
"name": "Soap"
},
"price": 85
},
{
"productName": "CCC",
"type": {
"id": 1,
"name": "Soap"
},
"price": 55
},
{
"productName": "DDD",
"type": {
"id": 2,
"name": "shampoo"
},
"price": 2
},
{
"productName": "EEE",
"type": {
"id": 2,
"name": "shampoo"
},
"price": 5
}
]
Expected Result:
{1},
[
{
"productName": "AAA",
"type": {
"id": 1,
"name": "Soap"
},
"price": 90
},
{
"productName": "BBB",
"type": {
"id": 1,
"name": "Soap"
},
"price": 85
},
{
"productName": "CCC",
"type": {
"id": 1,
"name": "Soap"
},
"price": 55
}],
{2},[
{
"productName": "DDD",
"type": {
"id": 2,
"name": "shampoo"
},
"price": 2
},
{
"productName": "EEE",
"type": {
"id": 2,
"name": "shampoo"
},
"price": 5
}
]