user3152131 user3152131 - 4 months ago 14
Javascript Question

angular 2 - how do I iterate through a JSON response that contains an object which contains an array of objects?

I am using a web api that my friend created, and here is a sample response:

{
types: [
{
id: 1,
contents: [
{
id: 1001,
perishable: 0
},
{
id: 1002,
perishable: 0
}
]
}
]
}


So if I get a response back that has 3 types of things in it, and each of those types has 3 contents, how can I use a repeater in this scenario below? I am able to get the type id correctly, but I am having trouble with repeating over the contents.

<div *ngFor="let type of response.types">
<h2>{{type.id}}</h2>
<!-- here I want to show basically divs for each of the objects in contents -->
<div *ngFor="what should I do here?">
<p>{{content.id}}</p>
<p>{{content.perishable}}</p>
</div>
</div>

Answer
<div *ngFor="let type of response.types">
  <h2>{{type.id}}</h2>

       <div *ngFor="let content of type.contents">
            <p>{{content.id}}</p>
            <p>{{content.perishable}}</p>
        </div>

</div>