How to loop over [object Object] using *ngFor

Viewed 1222

I am trying to loop through this array using *ngFor like this.

  let geographicalArea  = [{
    "_id": "5e77f43e48348935b4571fa7",
    "name": "Latin America",
    "employee": {
      "_id": "5e77c50c4476e734d8b30dc6",
      "name": "Thomas",
      "lastName": "Smith",
      "_v": 0
    },
    "_v": 0
  },
  {
    "_id": "5e77ff92165aa2060c54a5aa",
    "name": "Oceania",
    "employee": {
      "_id": "5e76c50c4476e734d8b30dc6",
      "name": "Joe",
      "lastName": "Duff",
      "_v": 0
    },
    "_v": 0
  }]

Html, but when i try to get the employee name it returns me Cannot read property 'name' of undefined

<tr *ngFor="let geo of geographicalArea | keyvalue">
                        <td>{{geo.value.name}}</td>
                        <td>{{geo.value.employee.name}}</td>
</tr>

i try to show only the employee but it return[object Object]

<tr *ngFor="let geo of geographicalArea | keyvalue">
                        <td>{{geo.value.name}}</td>
                        <td>{{geo.value.employee}}</td>
</tr>

I looked for the way to go through an object inside an object and I found the pipe keyvalue but it does not return the information of the employee, which would be the most appropriate way to obtain this information using this pipe

2 Answers

You don't need the keyvalue pipe to loop through geographicalArea because it is an array. However if you want to loop through each employee inside geographicalArea then you need keyvalue pipe because it is an object.

<tr *ngFor="let geo of geographicalArea">
  <td>{{geo.name}}</td>
  <td>{{geo.employee.name}}</td>
  <div *ngFor="let employee of geo.employee | keyvalue">
    {{ employee.key }} : {{ employee.value }}
  </div>
</tr>

You can loop over array and directly access inner object property, using dot operator.

<tr *ngFor="let geo of geographicalArea">
  <td>{{geo.name}}</td>
  <td>{{geo.employee.name}}</td>
</tr>
Related