Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

angular - how to filter array via dynamic filter selected via rxjs

i have an array of products here it is

  let products=[
    {id:1,category:[23,34],subcategory:[45,67],company:[56,78]}
    {id:2,category:[46,19],subcategory:[89,645],company:[16,88]}
]

and here is my dynamic filter array which i have to apply

 let filter=[
     {key:"category",values:[19]}
     {key:"company",values:[88,16]}
   ]

how can i dynamically filter the products array via rxjs here is my code which is working for only one filter , but i need for dynamicacally coming more then 1

here is my code for 1 filter i gave the type e.g

  type="category"
  values=[18,19]
 products.pipe(
            flatMap(response => response),
            filter(
                (product: any) => {
                    
                    return product[type].find((catnum) => values.includes(catnum))
                }
            ), toArray()
        ).subscribe(data => {}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I correctly understood you, you want to filter products array using if some of the condition in filter array is matched and this filter array may change over the time.
First of all, you should use map operator to modify products stream. And inside map operator you have to filter products which pass the condition.

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)
    })
  }

I have implemented it here, you can open console and see filtered results


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...