简体   繁体   中英

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. I can retrieve from normal JSON but not in Object format.

Typescript

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

The API JSON file is displayed this way:

{
  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:

  1. use the keyvalue pipe from angular: *ngFor item of data | keyvalue *ngFor item of data | keyvalue
  2. convert to an array using Object.values(data) or Object.entries(data) . the former gives you only the value object, the latter also the "numbers"

What you need to keep in mind: the returned object does not have a defined order. 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

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

which you can sort easily by the first tuple item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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