dhoffens
dhoffens

Reputation: 147

Angular: How do I Rxjs filter by property through an array of objects?

What is the correct way to apply an RXJS v5.5 filter to an array of objects?

I am getting back a json array that looks like this:

[
    0: {CompanyName: "Facebook Inc-A", Symbol: "FB", is_etf: false},
    1: {CompanyName: "Flagstar Bancp", Symbol: "FBC", is_etf: false},
    2: {CompanyName: "UBS AG FI Enhanced Large Cap Growth ETN", etf_data: {…}, Symbol: "FBGX", is_etf: true},
    3: {CompanyName: "Fortune Brd H&S", Symbol: "FBHS", is_etf: false},
    4: {CompanyName: "Fortress Biotec", Symbol: "FBIO", is_etf: false},
    5: {CompanyName: "First Bus Finl", Symbol: "FBIZ", is_etf: false},
...]

I need to keep values with is_etf === false

I currently have:

...

.switchMap(val => this.symbolSearchService.symbolLookup(val))
      .takeUntil(this.ngUnsubscribe)
      .filter((value) => {
        console.log(value)
        return true
      })
      .subscribe(val => {
        console.log('val', val)
        this.searchResults = val;
      });

symbolLookup returns the array referenced above. inside the filter I've tried:

value => !value.is_etf

value => return value.is_etf === false

value => value['is_etf'] === false

but none of these work, as the is_etf property is on each object, not on the value response. Before RXJS I would've just done a for loop and then just go with value[i]['is_etf'] etc but no luck here. All the reading materials I've encountered are doing simple filters like value => value > 2 ... any advice?

Thanks!!

Upvotes: 1

Views: 3390

Answers (1)

ggradnig
ggradnig

Reputation: 14159

The filter operator in RxJS does not behave like the Array.filter function used for filtering out items from a list.

What you are actually getting from this.symbolSearchService.symbolLookup(val) seems to be an array, so the type of the emmission in filter will also be an array. So, what you might be looking for is a map operator that forwards the filtered list, like that:

.switchMap(val => this.symbolSearchService.symbolLookup(val))
      .takeUntil(this.ngUnsubscribe)
      .map((values) => {
        return values.filter(v => !v.is_etf);
      })
      .subscribe(val => {
        console.log('val', val)
        this.searchResults = val;
      });

Upvotes: 2

Related Questions