【问题标题】:Angular pipe for nested arrays and objects | Recursive pipe嵌套数组和对象的角度管道 |递归管道
【发布时间】:2020-09-05 19:54:51
【问题描述】:

我有一个巨大的数组,里面有多个数组。我正在尝试使用角管对其进行过滤,但我只能通过第一级进行过滤。

这是DEMO

@Pipe({ name: 'myfilter' })
export class MyFilterPipe implements PipeTransform {
transform(users: any[], args): any {
return users.filter(user => user.itemName.toLowerCase().includes(args.toLowerCase()))
}

我需要过滤整个表格并显示与搜索文本匹配的结果

【问题讨论】:

  • 在示例中您只有一个级别
  • 您说您有一个带有嵌套数组的数组,但在示例中它只是一个对象数组,您的意思是这样吗?从您的链接中,我得到了我所期望的行为...您能解释一下仅通过第一级过滤是什么意思吗?
  • 对不起。我更新了示例。

标签: javascript angular ionic-framework


【解决方案1】:

您的搜索算法看起来不错(与项目名称匹配),但您没有搜索集合中最深的元素。为此,您只需将“用户”列表翻译成您想要搜索的内容。如果您将来要实现类似的东西,使用 TypeScript 类型可以帮助您确保提取正确的内容。这是一个写得很糟糕的实现,似乎适合您的情况。

@Pipe({ name: 'myfilter' })
export class MyFilterPipe implements PipeTransform {
  /**
   * In the future, replacing `any[]` with a type that actually
   * reflects the shape of your data will help you navigate
   * each of the properties.
   */
  transform(users: any[], args): any {
    return users.reduce((coll, top) => {
      // these nested reducers are bad, please don't
      // just copy and paste into your project
      if (top.subItemsList.length > 0) {
        return coll.concat(top.subItemsList.reduce((subColl, sub) => {
          if (sub.items.length > 0) {
            return subColl.concat(sub.items);
          }
          return subColl;
        }, []));
      }
      return coll;
    }, []).filter(user => user.itemName.toLowerCase().includes(args.toLowerCase()));
  }
}

StackBlitz 上的演示。

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 2016-09-05
    • 2020-07-16
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    相关资源
    最近更新 更多