如何使用 rxjs 过滤器在每个元素中过滤可变数量的类别

How to filter with a variable amount of categories in each element with rxjs filter

我正在尝试在我的 ionic/angular 应用程序中实现排序功能。该应用程序显示来自 API 的代金券,每张代金券都有不同的类别。我需要支持多个类别。我找到了一种方法来执行此操作,但是它要求每张凭证都具有 0 或 2 个类别才能正常运行。我希望能够更灵活地支持0,1,2类别的凭证。

它目前的工作方式是先过滤掉没有类别的凭证,然后检查类别数组,如果当前类别是数组的索引 0 或 1,如果没有第二个类别,则会给出索引错误。

      //Removing vouchers that have no category
      this.removeNoCats = from(this.searchvouchers).pipe(filter(item=> item.get_categories.length !== 0))

      this.removeNoCats.subscribe(res => console.log(res.name));

      //Filtering through vouchers with categories
      this.filteredList = from(this.removeNoCats)
      .pipe(filter((item:any) => item.get_categories[0].name === this.category || item.get_categories[1].name === this.category),toArray()) 

我怎样才能让它能够处理可变数量的类别?

因为get_categories是一个数组,你可以直接使用some方法:

.pipe(
  filter(item =>
    item.get_categories.some(category => category.name === this.category)
  )
)

这具有适用于任何大小的数组的优势,而不仅仅是 0 到 2。