在 Ionic 中使用键值过滤结果 subscribe()

Filter results subscribe() with keyvalue in Ionic

我想过滤 JSON 文件的结果,我已经用键值检索了数据列表。但我只想检索结果或父等于 null。

JSON 文件中的数据示例

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

这是我从 JSON 文件

中检索到的数据
this.http.get(api).subscribe((data) => {
    this.number = Object.keys(data).length;
    this.cats = data;
});

这里是 HTML 处理接收到的数据

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

您可以在订阅函数中进行过滤:

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

您的json返回的是一个对象,您需要先将其转换为数组。使用该数组,过滤其 parent 属性不是 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;
});