Dani
Dani

Reputation: 11

How to get the object value that is inside multiple arrays using angular and typescript?

I need help getting the item and color value of each of the array inside the total array

This is an example of my json

 "results ": {
"totals": {
  "total": [
    {
      "item": "car",
      "color": "red"
    },
    {
      "item": "car",
      "color": "white"
    },
    {
      "item": "bike",
      "color": "green"
    }
  ]
},

This is the typescript code I'm using the get the item and color from my json response

  let i = 0;
         this .items = response.results.totals.total.forEach((x)=>
              {
                this .item = x.item ;
                this .color = x.color;
               i++
              }
          

HTML

 <pre><strong>Item</strong>{{item}}</pre>
  <pre><strong>Color</strong>{{color}}</pre>

When I run my code I'm only able to display the first array inside the total array

Items : car 
Color: red

How I can get all the values inside the total array and display in my page using html so my output look like this ?

Items : car
Color: red
Items : car
Color: white
Items : bike
Color: green 

Upvotes: 1

Views: 972

Answers (1)

andsilver
andsilver

Reputation: 5972

this.items = response.results.totals.total;

Set the this.items as the array of the items you want to display.

And use ngFor for displaying the items in html:

<div *ngFor="let item of items">
  <pre><strong>Item</strong>{{item.item}}</pre>
  <pre><strong>Color</strong>{{item.color}}</pre>
</div>

Upvotes: 1

Related Questions