Trying to showcase my TypeScript data in a grouped format like this:
Make: Audi
Model - Year
R8 - 2012
RS5 - 2013
Make: Ford
Model - Year
Mustang - 2013
The JSON data I am working with is structured as follows:
this.cars = [
{
'make': 'audi',
'model': 'r8',
'year': '2012'
}, {
'make': 'audi',
'model': 'rs5',
'year': '2013'
}, {
'make': 'ford',
'model': 'mustang',
'year': '2012'
}, {
'make': 'ford',
'model': 'fusion',
'year': '2015'
}, {
'make': 'kia',
'model': 'optima',
'year': '2012'
},
];
I'm utilizing a function to group the data by "make" key, borrowed from this Stack Overflow link
groupBy(list: any, key: any) {
const newGroup = [];
list.forEach(item => {
const newItem = Object.assign({}, item);
delete newItem[key];
newGroup[item[key]] = newGroup[item[key]] || [];
newGroup[item[key]].push(newItem);
});
return newGroup;
}
In TypeScript, I've implemented the following logic:
this.vehicles = this.groupBy(this.cars, 'make');
However, in the view template, the data isn't displaying despite using this syntax:
<div class="row alert-success" *ngFor="let vehicle of vehicles">
{{vehicle}}
</div>
When checking the console log for `this.vehicles`, it outputs:
[audi: Array(2), ford: Array(2), kia: Array(1)]
audi: Array(2)
0: {model: "r8", year: "2012"}
1: {model: "rs5", year: "2013"}
length: 2
__proto__: Array(0)
ford: Array(2)
0: {model: "mustang", year: "2012"}
1: {model: "fusion", year: "2015"}
length: 2
__proto__: Array(0)
kia: Array(1)
0: {model: "optima", year: "2012"}
length: 1
__proto__: Array(0)
length: 0
__proto__: Array(0)