Search code examples
arraysobjectangularngfor

How to turn an [object Object] into an array?


I'm displaying some values from an API call into an ngFor directive. I'm trying to convert the data into an array. This is what i get from the server :

Data from the server

I subscribe the data like this :

 onVideoClick(video_id) {
    this._dashboardService.getVideoData(video_id)
      .subscribe(videoData => {
        if (videoData.ok) {
          console.log(videoData.json());
          this.videoData = videoData.json();
        } else {
          console.log('pas de données vidéos');
        }
      });
  }

I display my data this way :

     <tr>
        <th *ngFor="let vD of videoData">{{vD.attr_libelle}}</th>
     </tr>

How turn this Object into an array ?


Solution

  • You could implement a custom pipe for this. Here is a sample one that creates an array from object entries:

    @Pipe({name: 'keys'})
    export class KeysPipe implements PipeTransform {
      transform(value, args:string[]) : any {
        let keys = [];
        for (let key in value) {
          keys.push({key: key, value: value[key]);
        }
        return keys;
      }
    }
    

    and use it like that:

    <span *ngFor="#entry of content">           
      Key: {{entry.key}}, value: {{entry.value}}
    </span>
    

    Don't forget to add the pipe into the pipes attribute of the component where you want to use it.