繁体   English   中英

如何在 TypeScript 中迭代 JSON 属性

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

示例: https : //stackblitz.com/edit/keyvalue-pipe-qtaqnm

根据您的评论,我假设您想在 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>

组件.ts

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

html

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM