如何使用 *ngFor 迭代对象键 [英] How to iterate object keys using *ngFor

查看:36
本文介绍了如何使用 *ngFor 迭代对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Angular 2 中使用 *ngFor 迭代 [object object].

问题是对象不是对象数组,而是包含更多对象的对象对象.

<代码>{数据": {身份证":834,"first_name": "GS","last_name": "沙希德","电话": "03215110224",角色":空,"email": "test@example.com","picture": **{ <-- 我想得到 thumb: url 但无法获取 **网址":空,拇指":{网址":空}},"address": "尼什塔尔殖民地","city_id": 2,"provider": "email",uid":test@example.com"}}

我知道我们可以使用管道来迭代对象,但是我们如何从一个对象到另一个对象进一步迭代意味着data->picture->thum:url.

解决方案

Angular 6.0.0

https://github.com/角度/角度/blob/master/CHANGELOG.md#610-2018-07-25

引入了一个KeyValuePipe

另见https://angular.io/api/common/KeyValuePipe

<块引用>

@Component({选择器:'键值管道',模板:`<p>对象</p><div *ngFor="let item of object | keyvalue">{{item.key}}:{{item.value}}

<p>地图</p><div *ngFor="let item of map | keyvalue">{{item.key}}:{{item.value}}

</span>`})导出类 KeyValuePipeComponent {对象:{[key: number]: string} = {2: 'foo', 1: 'bar'};map = new Map([[2, 'foo'], [1, 'bar']]);}

原创

你可以使用管道

@Pipe({ name: 'keys', pure: false })导出类 KeysPipe 实现 PipeTransform {变换(值:任何,参数:任何[] = null):任何{return Object.keys(value)//.map(key => value[key]);}}

另请参阅如何使用 *ngFor 迭代对象键?

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.

Angular 6.0.0

https://github.com/angular/angular/blob/master/CHANGELOG.md#610-2018-07-25

introduced a KeyValuePipe

See also https://angular.io/api/common/KeyValuePipe

@Component({
  selector: 'keyvalue-pipe',
  template: `<span>
    <p>Object</p>
    <div *ngFor="let item of object | keyvalue">
      {{item.key}}:{{item.value}}
    </div>
    <p>Map</p>
    <div *ngFor="let item of map | keyvalue">
      {{item.key}}:{{item.value}}
    </div>
  </span>`
})
export class KeyValuePipeComponent {
  object: {[key: number]: string} = {2: 'foo', 1: 'bar'};
  map = new Map([[2, 'foo'], [1, 'bar']]);
}

original

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]);
    }
}

<div *ngFor="let key of objs | keys">

See also How to iterate object keys using *ngFor?

这篇关于如何使用 *ngFor 迭代对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆