-1

I have this array :

grp = [ {model: "CF650-3C", color: {Orange: 3, Black: 2} }, {model: "HD4533F", color: {Black: 2, Orange: 1} } ]

Those are objects in there that have .model and .color properties and I want to display them in a table so I need access to all .color values in there individually. So far I've tried iterating over like this:

<table class="table table-striped" >
<thead>
  <tr  >
    <th scope="col">Model</th>
    <th scope="col">color</th>
  </tr>
</thead>
<tbody>
  <ng-container *ngFor="let g of grp">
  <tr >
   
    <td>{{ g.model }}</td>
    <td>{{ g.color | json }}</td>

  </tr>
</ng-container>
</tbody>

Problem is it gets displayed like this and I don't know how to access the different .color keys and values

CF650-3C    { "Orange": 3, "Black": 2 } 
HD4533F     { "Black": 2, "Orange": 1 } 
doctorprofessor
  • 105
  • 1
  • 2
  • 8

3 Answers3

1

Some practices you can use:

Iterating the values by using keyvalue pipe

  <ng-container *ngFor="let g of grp">
  <tr >
    <td>
     <div *ngFor="let c of g.color | keyvalue">
      Key: <b>{{c.key}}</b> and Value: <b>{{c.value}}</b>
     </div>
    </td>
    <td>{{ g.model }}</td>
  </tr>
 </ng-container>

Create a component and set your object as @input StackBlitz

  <ng-container *ngFor="let g of grp">
  <tr >
    <td>
     <app-color [Color]="g.color"></app-color>
    </td>
    <td>{{ g.model }}</td>
  </tr>
 </ng-container>

Create a custom pipe that return a value based on your object UltimateCourses

  <ng-container *ngFor="let g of grp">
  <tr >       
    <td>{{ g.model }}</td>
    <td>{{ g.color | mycolorpipe }}</td>    
  </tr>
</ng-container>
ShayD
  • 689
  • 7
  • 17
1

You can do it like this:

<ng-container *ngFor="let g of grp">
  <tr >
   
    <td>{{ g.model }}</td>
    <td>{{ Object.keys(g.color) }}</td>

    <td>{{ Object.values(g.color) }}</td>

  </tr>
</ng-container>
Amrit
  • 2,115
  • 1
  • 21
  • 41
0

You have to iterate through the color object *ngFor="let c of g.color"

Duki
  • 91
  • 4