Jason Jason - 1 month ago 10
Javascript Question

loop through associative array of objects

I have an array of objects, and I want to get the name of the cars with the same id and display their name and year like this:

ferrai 01-02-2000, 10-23-2010

lambo 08-12-2018, 02-02-2012

NOT like this:

ferrai 01-02-2000

ferrai 10-23-2010

lambo 08-12-2018

lambo 02-02-2012

cars = [

[0] : { year: "01-02-2000"
sport:{id: "1111", name: "ferrai"}

}

[1] : { year: "10-23-2010"
sport:{id: "1111", name: "ferrari"}

}

[2] : {year: "08-12-2018"
sport:{id: "2222", name: "lambo"}

}

[3] : {year: "02-02-2012"
sport:{id: "2222", name: "lambo"}

}

]


how would I be able to do this in angular2+?
I have tried this code:

.html file

<div *ngFor="let obj of cars">
<div *ngFor="let name of obj.sport">
<div>{{getCars(name)}}</div>
</div>
</div>


.ts file

getCars(obj){
var sport = obj.sport;
var year = obj.year;

//do stuff

}


I appreciate any help!

Answer Source

I personally would "massage" the data first before having the DOM render things. I personally like to do a lot of the work to the data (either on the server side or before it reaches some DOM iterator to build elements) so that the view can be as simple as possible. Here's what I would do (fixed a typo and this is vanilla javascript):

cars = [
  {
    year: "01-02-2000",
    sport:{id: "1111",  name: "ferrari"}

  },
  {
    year: "10-23-2010",
    sport:{id: "1111", name: "ferrari"}
  },
  {
    year: "08-12-2018",
    sport:{id: "2222", name: "lambo"}
  },
  {
    year: "02-02-2012",
    sport:{id: "2222", name: "lambo"}
  }
]

newCarsData = cars.reduce((acc, curr) => {
  if (!acc.hasOwnProperty(curr.sport.name)) {
    acc[curr.sport.name] = {};
    acc[curr.sport.name].years = []
  }

  acc[curr.sport.name].years.push(curr.year);
  return acc;
}, {});

console.log(newCarsData);

Now you'll have this data structure:

{
  ferrari: { 
    years: [ '01-02-2000', '10-23-2010' ]
  },
  lambo: {
    years: [ '08-12-2018', '02-02-2012' ]
  }
}

and that's easy for a repeat in angular or any framework