Loop through array of JSON object with *ngFor (Angular 4)

BlueCat picture BlueCat · Jan 23, 2018 · Viewed 26.8k times · Source

I want to loop through an array of objects, which is in my json file.

Json

[
  {
    "name": "Mike",
    "colors": [
      {"name": "blue"},
      {"name": "white"}
    ]
  },

  {
    "name": "Phoebe",
    "colors": [
      {"name": "red"},
      {"name": "yellow"}
    ]
  }
]

html

<div *ngFor="let person of persons">
   <p>{{person.name}}</p> <!-- this works fine-->
   <p *ngFor="let color of person.colors"> <!--I want to list the colors of the person here-->
     {{color.name}}
   </p>
</div>

I cant access the colors array of a person. How do I achieve that?

I've already looked at these posts but the solutions of them couldn't help me:

Angular2 ngFor Iterating over JSON

Angular2 - *ngFor / loop through json object with array

Answer

Vivek Doshi picture Vivek Doshi · Jan 23, 2018

For Angular 6.1+ , you can use default pipe keyvalue ( Do review also ) :

<ul>
    <li *ngFor="let recipient of map | keyvalue">
        {{recipient.key}} --> {{recipient.value}}
    </li>
</ul>

WORKING DEMO


Previously : As you are saying :

Angular2 - *ngFor / loop through json object with array , this couldn't help you

You dont have any need of that, coz your code works fine , please check

WORKING DEMO