简体   繁体   English

Foreach Json 结果离子 Angular

[英]Foreach Json results Ionic Angular

I would like to be able to retrieve the results from a JSON file but I cannot find the solution.我希望能够从 JSON 文件中检索结果,但我找不到解决方案。 I can retrieve from normal JSON but not in Object format.我可以从正常的 JSON 中检索,但不能以 Object 格式检索。

Typescript Typescript

this.http.get('http://example.com/api')
  .subscribe((data) => {
    console.log(data);
  });

The API JSON file is displayed this way: API JSON 文件以这种方式显示:

{
  1: {id:1, name: "string"}
  2: {id:1, name: "string"}
  3: {id:1, name: "string"}
  4: {id:1, name: "string"}
}

I would like to be able to make a loop of this data afterwards之后我希望能够对这些数据进行循环

<ion-item *ngFor="let item of data" >
  <div>
    {{item.name}}
  </div>
</ion-item>

Thank you in advance先感谢您

Here is the answer to my problem:这是我的问题的答案:

<ion-item *ngFor="let item of data | keyvalue" >
  <div>
    {{ item.key }} {{ item.value['data'] }}
  </div>
</ion-item>

You have multiple possibilities to loop over this response object:您有多种可能循环此响应 object:

  1. use the keyvalue pipe from angular: *ngFor item of data | keyvalue使用来自keyvalue的键值 pipe: *ngFor item of data | keyvalue *ngFor item of data | keyvalue
  2. convert to an array using Object.values(data) or Object.entries(data) .使用Object.values(data)Object.entries(data)转换为数组。 the former gives you only the value object, the latter also the "numbers"前者只给你值 object,后者也是“数字”

What you need to keep in mind: the returned object does not have a defined order.您需要记住:返回的 object 没有定义的顺序。 So if you use either method, the order of the iteration is not defined and COULD be random.因此,如果您使用任何一种方法,迭代的顺序都没有定义,并且可能是随机的。

It MAY be right on your machine/browser but you SHOULD NOT rely on it.它可能在您的机器/浏览器上是正确的,但您不应该依赖它。 Therefore make sure to sort your data AFTER converting it to an array (if the data is supposed to be ordered).因此,请确保在将数据转换为数组之后对其进行排序(如果数据应该是有序的)。

If the order is given by the "numeric" keys in the original object, i would recommend to use Object.entries , wich will give you an array of key-value tuples如果订单是由原始 object 中的“数字”键给出的,我建议使用Object.entries ,它会给你一个键值元组数组

[[1, {id:1, name: "string"}], [...], ...]

which you can sort easily by the first tuple item.您可以按第一个元组项目轻松排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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