簡體   English   中英

如何使用 *ngFor 迭代 object 密鑰

[英]How to iterate object keys using *ngFor

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

問題是 object 不是 object 的數組,而是 object 的 object 的數組,其中包含更多對象。

{

  "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 .

角度 6.0.0

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

引入了一個KeyValuePipe

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

原來的

你可以使用管道

@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">

另請參閱如何使用 *ngFor 迭代對象鍵?

我認為最優雅的方法是使用這樣的 javascript Object.keys (我首先為此實現了一個管道,但對我來說,它只是使我的工作變得不必要):

在組件傳遞對象到模板中:

Object = Object;

然后在模板中:

<div *ngFor="let key of Object.keys(objs)">
   my key: {{key}}
   my object {{objs[key] | json}} <!-- hier I could use ngFor again with Object.keys(objs[key]) -->
</div>

如果你有很多子對象,你應該創建一個組件來為你打印對象。 通過根據需要打印值和鍵,並在遞歸調用自身的子對象上。

海爾你可以找到這兩種方法的stackblitz演示。

我知道這個問題已經得到回答,但我有一個解決方案。

您還可以在*ngFor使用Object.keys()來獲得所需的結果。

我在stackblitz上創建了一個演示。 我希望這會對您/其他人有所幫助/指導。

代碼片段

HTML代碼

<div *ngFor="let key of Object.keys(myObj)">
  <p>Key-> {{key}} and value is -> {{myObj[key]}}</p>
</div>

.ts 文件代碼

Object = Object;

myObj = {
    "id": 834,
    "first_name": "GS",
    "last_name": "Shahid",
    "phone": "1234567890",
    "role": null,
    "email": "test@example.com",
    "picture": {
        "url": null,
        "thumb": {
            "url": null
        }
    },
    "address": "XYZ Colony",
    "city_id": 2,
    "provider": "email",
    "uid": "test@example.com"
}

您必須創建自定義管道。

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

然后在你的 *ngFor 中使用它

*ngFor="let item of data | keyobject"

在 Angular HTML 模板中循環 object

keyValuePipe 在 Angular 中引入: 請參考https://angular.io/api/common/KeyValuePipe

快速代碼:

<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>

1.創建自定義管道以獲取密鑰。

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. 在角度模板文件中,您可以使用 *ngFor 並迭代您的對象對象
<div class ="test" *ngFor="let key of Obj | keys">
    {{key}}
    {{Obj[key].property}
<div>

Angular 現在為這種場景提供了一種迭代對象類型,稱為 Set。 當我發現這個問題正在搜索時,它符合我的需求。 您創建集合,像“推”到數組一樣“添加”到它,然后像數組一樣將其放入 ngFor 中。 沒有管道或任何東西。

this.myObjList = new Set();

...

this.myObjList.add(obj);

...

<ul>
   <li *ngFor="let object of myObjList">
     {{object}}
   </li>
</ul>

如果您在響應中使用map()運算符,則可以將toArray()運算符鏈接到它...然后您應該能夠遍歷新創建的數組...至少對我有用:)

在對模板中的嵌套循環進行了大量故障排除后,我發現這對我的使用效果更好:

(一方面我試圖迭代 agm-polygon 並且它不會讓我嵌套 div)。

在 component.ts 中:

Object = Object

values= Object.values(this.arrayOfObjects)

在組件中。html:

<div *ngFor='let value of values'>{{value.property}}</div>

一旦你檢索了值,你就擁有了一個 Iterable,並且不需要擔心還遍歷模板中的鍵,這可能會變得復雜並且看起來很亂。

我會這樣做:

<li *ngFor="let item of data" (click)='onclick(item)'>{{item.picture.url}}</li>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM