Home > Software engineering >  How can I iterate through object of objects data to fill angular table
How can I iterate through object of objects data to fill angular table

Time:05-21

I'm having a hard time trying to iterate data fetched from api through angular bootstrap table. From a first approach I was mapping the data to prsnl variable declared as prsnl: any and initialized in the function bellow:

getAllPersnlValues(data) {
   
    return this.persnlService.getPersnl(data)
    .pipe(
      map((response) => response)
    ).subscribe((res) => {this.prsnl = res; console.log('prsnl', this.prsnl)});
  }

In the Html side I had:

       <table >
          <thead>
            <tr>
              <th scope="col">ID</th>
              <th scope="col">FULL NAME</th>
            </tr>
          </thead>
   
            <tbody>
              <tr *ngFor = "let pr of prsnl">
                <th scope="row">1</th>
                <td>{{pr.result.fullName}}</td>
              </tr>
            </tbody>
        </table>

Because the api's response is an object of objects as on screenshot bellow: enter image description here

As you can see on console the api response was properly assign to the prsnl varaiable from the getAllPersnlValues() method, but iterating through it in the table failed because table remains empty.

I then got to understand that I needed to transform prsnl type which is object of object into array of object so that *ngFor may perform the iteration, and I'm now using keyval from KeyValuePipe to transform the api's response into array, as you can see in the code bellow:

getAllPersnlValues(data) {
    console.log('data', data);
   
    return this.persnlService.getPersnl(data)
    .pipe(
      map((response) => {
        if(typeof response !== 'undefined') this.keyval.transform(response)
      })).subscribe((res) => {this.prsnl = res; console.log('prsnl', this.prsnl)})
  }

But doing this cause the project to not compile, and it only compiles when I remove the KeyValuePipe importation from app.module.ts, and I realize that the subscribe() function does not console.log this.prsnl value. How can I then make this work with response being object of object and display it inside the table. I will really appreciate your help to tackle this impedement. Thanks in advance.

CodePudding user response:

You're trying to iterate over an object using the *ngFor directive which isn't natively supported. You'd need to use keyvalue pipe to do that.

But seeing your logs, the required array is contained in the result property. So try the following

<tr *ngFor = "let res of prsnl?.result">
  <th scope="row">1</th>
  <td>{{ res?.fullName }}</td>
</tr>
  • Related