[英]How to Iterate JSON properties in TypeScript
My question is very simple, I have a following JSON Typescript Object and I like to Iterate trought the JSON properties我的问题很简单,我有一个以下 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"}
The code used is the following angular TypeScript component:使用的代码是以下有角度的 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);
}
}
What I really need is to go through the key-value attributes of the JSON and show them in my HTML.我真正需要的是遍历 JSON 的键值属性并将它们显示在我的 HTML 中。
Many Thanks!非常感谢!
If you are using angular 6.1 use keyvalue pipe如果您使用的是 angular 6.1,请使用键值管道
<div *ngFor="let title of data | keyvalue">
{{title.key}}
</div>
For Angular 5对于 Angular 5
<div *ngFor="let key of dataKeys">
{{key}} ------------- {{data[key]}}
</div>
get dataKeys() { return Object.keys(this.data); }
Example: https://stackblitz.com/edit/keyvalue-pipe-qtaqnm示例: https : //stackblitz.com/edit/keyvalue-pipe-qtaqnm
As per your comment, I'm assuming you want to do an ngFor on the HTML to display each one of the key-value pairs根据您的评论,我假设您想在 HTML 上执行 ngFor 以显示每个键值对
<div *ngFor="let key of Object.keys(properties)">
{{properties[key]}} --> this is the value
</div>
You can get all the keys using Object.Keys and assign to a variable as follows,您可以使用 Object.Keys 获取所有键并分配给一个变量,如下所示,
this.properties=JSON.parse(this.values);
let response = Object.keys(this.propertie);
now you can use ngFor over it,现在你可以使用 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>
unfortunately seems to be NOT working (with keyvalue) with ANGULAR_9不幸的是,似乎不适用于 ANGULAR_9(使用键值)
see here for a comparison of full different way of doing: https://stackblitz.com/edit/angular9-iterate-on-object-attribute有关完全不同的操作方式的比较,请参见此处: https : //stackblitz.com/edit/angular9-iterate-on-object-attribute
otherwise the answer by defining a method to do the job is still working.否则,通过定义一种方法来完成这项工作的答案仍然有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.