I am building an Angular 9 app. In this app I have a dynamically fetched JSON array. I need to take the JSON array and then extract and group based upon the keys. Example array:
const collection = [{
title: 'Product A',
price: 234,
cost: 234
}, {
title: 'Product B',
price: 100,
cost: 200
}, {
title: 'Product C',
price: 344,
cost: 55
}, {
title: 'Product D',
price: 222,
cost: 332
}];
I can mange to extract individual keys but I want to have a method that takes any JSON array and then extract and group per key.
This is my code for extracting individual keys. I had to hard code the key name (title).
groupByKey(array, key) {
return array.map(a => a.title);
}
This is what I want to transform the original JSON array to:
[{
header: "title",
rows: ["Product A", "Product B", "Product C", "Product D"]
}, {
header: "price",
rows: [234, 100, 344, 222]
}, {
header: "cost",
rows: [234, 200, 55, 332]
}]