Search code examples
angularionic-frameworkobservableionic4

Filter results subscribe() with keyvalue in Ionic


I would like to filter the results of a JSON file, I already retrieve the list of data with keyvalue. But I would like to retrieve only the results or parent equals null.

Example of the data present in the JSON file

{
    "1": {
        "id": 1,
        "name": "Example name",
        "parent": null,
    },
    "2": {
        "id": 1,
        "name": "Example name",
        "parent": 12,
    }
}

Here is my data retrieved from a JSON file

this.http.get(api).subscribe((data) => {
    this.number = Object.keys(data).length;
    this.cats = data;
});

And here is the HTML which processes the received data

<ion-row>
    <ion-col *ngFor="let item of cats | keyvalue" size="6">
        {{ item.value['name'] }}
    </ion-col>
</ion-row>

Solution

  • Your json returned is an object, and you would need to convert it to array first. With that array, filter where its parent properties isn't null

    
    this.http.get(api).subscribe((data) => {
        //convert it to an array, ignoring the keys
        objList = Object.values(data) 
        // now filter
        this.cats = objList.filter(cat=>cat.parent !== null)
        // assign the length of array to this.number
        this.number = this.cats.length;
    });