[英]How to Iterate JSON properties in TypeScript
我的問題很簡單,我有一個以下 JSON Typescript 對象,我喜歡通過 JSON 屬性進行迭代
{"work_type":"Fabricación","work_type_resp":"Mesa","looking_for":"Relación Calidad/Precio","image":"https://s3-sa-east-1.amazonaws.com/online-quotation-images/153366018967.png","width":"22","high":"34","depth":"","modifications":"mod"}
使用的代碼是以下有角度的 TypeScript 組件:
export class DetailsOnlineQuoteModalComponent implements OnInit {
@Input() title;
@Input() values:string;
properties:JSON;
constructor(public activeModal: NgbActiveModal) { }
ngOnInit() {
this.properties=JSON.parse(this.values);
console.log(this.properties);
}
}
我真正需要的是遍歷 JSON 的鍵值屬性並將它們顯示在我的 HTML 中。
非常感謝!
如果您使用的是 angular 6.1,請使用鍵值管道
<div *ngFor="let title of data | keyvalue">
{{title.key}}
</div>
對於 Angular 5
<div *ngFor="let key of dataKeys">
{{key}} ------------- {{data[key]}}
</div>
get dataKeys() { return Object.keys(this.data); }
根據您的評論,我假設您想在 HTML 上執行 ngFor 以顯示每個鍵值對
<div *ngFor="let key of Object.keys(properties)">
{{properties[key]}} --> this is the value
</div>
您可以使用 Object.Keys 獲取所有鍵並分配給一個變量,如下所示,
this.properties=JSON.parse(this.values);
let response = Object.keys(this.propertie);
現在你可以使用 ngFor 了,
<div *ngFor="let key of response ">
{{properties[key]}}
</div>
let obj = {"work_type":"Fabricación","work_type_resp":"Mesa","looking_for":"Relación Calidad/Precio","image":"https://s3-sa-east-1.amazonaws.com/online-quotation-images/153366018967.png","width":"22","high":"34","depth":"","modifications":"mod"}
this.keyOfObj = Object.keys(obj);
<div *ngFor="let key of keyOfObj ">
{{obj[key]}}
</div>
不幸的是,似乎不適用於 ANGULAR_9(使用鍵值)
有關完全不同的操作方式的比較,請參見此處: https : //stackblitz.com/edit/angular9-iterate-on-object-attribute
否則,通過定義一種方法來完成這項工作的答案仍然有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.