snowflakes74
snowflakes74

Reputation: 1307

How to display grouped data in typescript using *ngFor

I am trying to display data in typescript as grouped data in the following format :

Make: Audi
  Model  -  Year
   R8    -   2012
   RS5   -   2013
Make: Ford
  Model   -  Year
  Mustang -   2013   

My data (json) in the following format :

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'
  },
];

and I am using this function to group it by "make" and it returns a new array grouped by "make". I have used this function from the following link of SOF enter link description here

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 the typescript I have done the following :

this.vehicles = this.groupBy(this.cars, 'make');

and in the view I have the following syntax but nothing is getting displayed on the screen

 <div class="row alert-success" *ngFor="let vehicle of vehicles">
       {{vehicle}}
 </div>

If I have do console.log(this.vehicles) I get the following output:

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

Upvotes: 0

Views: 313

Answers (2)

shshsi
shshsi

Reputation: 106

vehicles is a 2d array so you have to loop twice -

 <div class="row alert-success" *ngFor="let vehicles of vehiclesArray">
      <div *ngFor= "let vehicle of vehicles">
        {{vehicle.model}} {{vehicle.year}}
      </div>
 </div>

Upvotes: 2

abhay tripathi
abhay tripathi

Reputation: 4022

Update your {{vehicle}} to this

{{vehicle.model}} {{vehicle.year}}

Upvotes: 0

Related Questions