How to iterate object keys using *ngFor

匿名 (未验证) 提交于 2019-12-03 01:52:01

问题:

I want to iterate [object object] using *ngFor in Angular 2.

The problem is the object is not array of object but object of object which contains further objects.

{    "data": {     "id": 834,     "first_name": "GS",     "last_name": "Shahid",     "phone": "03215110224",     "role": null,     "email": "test@example.com",     "picture": **{ <-- I want to get thumb: url but not able to fetch that**       "url": null,       "thumb": {         "url": null       }     },     "address": "Nishtar Colony",     "city_id": 2,     "provider": "email",     "uid": "test@example.com"   } }

I know we can use pipe to iterate the object but how we can iterate further from object to object means data->picture->thum:url.

回答1:

You can use a pipe

@Pipe({ name: 'keys',  pure: false }) export class KeysPipe implements PipeTransform {     transform(value: any, args: any[] = null): any {         return Object.keys(value)//.map(key => value[key]);     } }

See also How to use *ngFor with Object?



回答2:

I think the most elegant way to do that is to use the javascript Object.keys like this:

in the Component pass Object to template:

Object = Object;

then in the template:

my key: {{key}} my object {{objs[key] | json}}


回答3:

You have to create custom pipe.

import { Injectable, Pipe } from '@angular/core'; @Pipe({    name: 'keyobject' }) @Injectable() export class Keyobject {  transform(value, args:string[]):any {     let keys = [];     for (let key in value) {         keys.push({key: key, value: value[key]});     }     return keys; }}

And then use it in your *ngFor

*ngFor="let item of data | keyobject"


回答4:

If you are using a map() operator on your response,you could maybe chain a toArray() operator to it...then you should be able to iterate through newly created array...at least that worked for me :)



回答5:

1.Create a custom pipe to get keys.

import { Pipe, PipeTransform } from '@angular/core';  @Pipe({   name: 'keys' }) export class KeysPipe implements PipeTransform {    transform(value: any, args?: any): any {     return Object.keys(value);   } }
  1. In angular template file, you can use *ngFor and iterate over your object object
{{key}} {{Obj[key].property}


回答6:

i would do this:

  • {{item.picture.url}}


  • 标签
    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!