Home > Mobile >  Angular - How to Iterate through an object that some of the keys are undefined
Angular - How to Iterate through an object that some of the keys are undefined

Time:11-01

So I have objectA and objectB

objectA {
    0: {name: 'M', date: '2021-10-24'}
    1: {name: 'T', date: '2021-10-25'}
    2: {name: 'W', date: '2021-10-26'}
    3: {name: 'T', date: '2021-10-27'}
    4: {name: 'F', date: '2021-10-28'}
    5: {name: 'S', date: '2021-10-29'}
    6: {name: 'S', date: '2021-10-30'}
}

objectB {
    2021-10-29: [{…}]
    2021-10-30: [{…}, {…}]
}

objectA holds all the days in the current week and objectB holds all the appointments(building an appointments app) in the current week, so objectB can have an appointment every day, having the dates of the appointments as keys or it can have only one, two or even 0 date keys, depending if there are appointments or not. In the above example there is only one appointment on the 29'th and two on the 30'th.

My problem is that I want to iterate through objectB in the HTML(to get some appointment data) by getting the keys(the date strings) from objectA. I get this Error and the iteration stops because the key I'm trying to access does not exist.

ERROR:

ERROR TypeError: Cannot read properties of undefined (reading '2021-10-24')

This is my HTML:

 <tbody>
     <tr>
         <td *ngFor="let day of objectA">
             <div *ngFor="let app in objectB[day.date]">
                 <span *ngIf="app">{{ app.startTime | date : 'HH:mm' }}</span>
             </div>         
         </td>
     </tr>
 </tbody>

So I guess my question is how do I iterate through objectB without knowing all its keys, or how to make the for loop ignore the undefined and just continue to iterate.

Thanks!

CodePudding user response:

Solution 1

You need KeyValuePipe to iterate for the object in order to get keys and values.

<td *ngFor="let kv of objectA | keyvalue;">
  <div *ngFor="let app of objectB[kv.value.date]">
    <span *ngIf="app">{{ app.startTime | date: 'HH:mm' }}</span>
  </div>
</td>

Sample Solution 1 on StackBlitz


Solution 2

Convert objectA to array with Object.keys().

aList = Object.keys(this.objectA).map((x: any) => this.objectA[x]);
<td *ngFor="let day of aList;">
  <div *ngFor="let app of objectB[day.date]">
    <span *ngIf="app">{{ app.startTime | date: 'HH:mm' }}</span>
  </div>
</td>

Sample Solution 2 on StackBlitz

CodePudding user response:

<tbody>
 <tr>
     <td *ngFor="let day of objectA">
<ng-container *ngIf="objectB[day.date]">
         <div *ngFor="let app in objectB[day.date]">
             <span *ngIf="app">{{ app.startTime | date : 'HH:mm' }}</span>
         </div>   
</ng-container>

  
   </td>
 </tr>
 </tbody>

Just add an if condition and check if that key exist in ObjectB then loop thought it

  • Related