如何在TypeScript中迭代JSON属性

3

我的问题很简单,我有一个下面的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"}

使用的代码是以下Angular 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中显示它们。非常感谢!

你想在HTML或TS中访问键值对的位置在哪里? - Chellappan வ
你好,在HTML中 - AlejoDev
在 TypeScript 中,不存在所谓的 JSON 对象。 - str
5个回答

13

如果您正在使用 Angular 6.1,请使用 keyvalue 管道。

<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


我正在使用 Angular 5。 - AlejoDev
1
请在您的回答中说明如何创建dataKeys - Ashish Ranjan
Angular 5 的答案也适用于 Angular 9(keyvalue 也不起作用)。 - Alexis_D
嗨,Chellapan,实际上在使用模型初始化对象数据时出现了错误。(或者在我的示例中是人,请在此处查看更多详细信息=> https://stackblitz.com/edit/angular9-iterate-on-object-attribute) - Alexis_D
如文档https://angular.io/api/common/KeyValuePipe#input-value中所述,您必须使用接口来描述可索引类型。将您的接口更改为以下内容:export class Person{ [key: string]: string, name:string; surname:string; location:string; age:string; } - Chellappan வ

5
根据您的评论,我假设您想在HTML上执行ngFor以显示每个键值对。
<div *ngFor="let key of Object.keys(properties)">
  {{properties[key]}} --> this is the value
</div>

4
您可以使用Object.Keys获取所有键,并将其分配给一个变量,如下所示:
this.properties=JSON.parse(this.values);
let response = Object.keys(this.propertie);

现在您可以在其上使用ngFor,
<div *ngFor="let key of response ">
  {{properties[key]}}  
</div>

0

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

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接