【问题标题】:Filter for nested data structure过滤嵌套数据结构
【发布时间】:2022-01-22 07:33:19
【问题描述】:

我想默认显示我页面上的所有数据。但是如果用户在搜索字段中添加了一些关键字,那么我想通过他们的 uiUnits ID 过滤显示的数据。

数据结构,仪表板:

[
    {
        "id": "interface A",
        "uiUnits": [
            {
                "type": "widget",
                "id": "abc"
            },
            {
                "type": "widget",
                "id": "xyz"
            }
        ]
    },
    {
        "id": "interface B",
        "uiUnits": [
            {
                "type": "widget",
                "id": "zzz"
            }
        ]
    }
]

component.html

<input type="search" [(ngModel)]="searchTerm">
<button (click)="filterUnits(searchTerm)"></button>
<div *ngFor="item of dashboard">
    <div *ngFor="unit of item.uiUnits">
        <p>{{ unit.id }}</p>
        <p>{{ unit.type }}</p>
    </div>
</div>

组件.ts

dashboard: Dashboard;

filterUnits(data: string) {
    this.dashboard.filter((x) =>
        x.uiUnits.id.toLowerCase().indexOf(data.toLowerCase()) > -1);
    return this.dashboard;
}

filterUnits 功能不起作用,有人可以帮我解决一下吗?

【问题讨论】:

  • uiUnits 是一个array,因此您无法访问属性id,您需要遍历其元素。

标签: angular typescript angular9


【解决方案1】:

正如评论中提到的@akotech,您需要使用uiUnits 数组进行迭代以过滤id

您必须将过滤后的结果分配回this.dashboard,以便反映其值。

filterUnits(data: string) {
  this.dashboard = this.dashboard.filter(
    (x) =>
      x.uiUnits.find(
        (y) => y.id.toLowerCase().indexOf(data.toLowerCase()) > -1
    )
  );
}

通过上述过滤逻辑,通过“abc”过滤,将显示具有uiUnitsid: abc的项目(interface A)。

abc

小部件

xyz

小部件


附加

如果您需要返回仅匹配idsearchTermuiUnits' 元素,您可以使用下面的过滤逻辑:

  1. 按搜索词过滤 uiUnits 数组。
  2. Array.map()产生一个新数组,当uiUnits既不是空也不是空数组时,创建一个新对象并将uiUnits附加到对象上。否则,返回null
this.dashboard = this.dashboard.map((x) => {
  let uiUnits = x.uiUnits.filter(
    (y) => y.id.toLowerCase() == data.toLowerCase()
  );

  return uiUnits
    ? {
        ...x,
        uiUnits: [...uiUnits],
      }
    : null;
});

Sample Demo on StackBlitz

【讨论】:

    猜你喜欢
    • 2016-10-29
    • 2015-03-30
    • 2015-07-21
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2014-04-27
    相关资源
    最近更新 更多