如何解决如何通过通过rxjs选择的动态过滤器过滤数组
这里有很多产品
let products=[
{id:1,category:[23,34],subcategory:[45,67],company:[56,78]}
{id:2,category:[46,19],subcategory:[89,645],company:[16,88]}
]
这是我必须应用的动态过滤器数组
let filter=[
{key:"category",values:[19]}
{key:"company",values:[88,16]}
]
我如何通过 rxjs 动态过滤产品数组 这是我的代码,仅适用于一个过滤器,但是我需要动态地增加1以上的值
这是我为1个过滤器指定的代码,例如
type="category"
values=[18,19]
products.pipe(
flatMap(response => response),filter(
(product: any) => {
return product[type].find((catnum) => values.includes(catnum))
}
),toArray()
).subscribe(data => {}
解决方法
如果我对您的理解正确,那么您想使用 filter 数组中的某些条件匹配并且此 filter 数组随时间变化的条件来过滤产品数组。
首先,您应该使用 map 运算符修改产品流。在地图运算符内部,您必须过滤通过条件的产品。
this.products$
.pipe(
map((products) => {
return products.filter((product) => {
return this.filters.some((filter) => this.isProductMeetFilterConditions(product,filter))
})
})
)
private isProductMeetFilterConditions(product: Product,filter: Filter): boolean {
return filter.values.some((value) => {
return product[filter.key].includes(value)
})
}
我已经实现了here,您可以打开控制台并查看过滤的结果
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。