Matthis.h
Matthis.h

Reputation: 909

Use Array.filter on object array in observable

I want add filter on my object array. I try this :

this.projects
      .pipe(
          map(arr => {
              console.error(arr);
              arr.filter(r => r.name == 'x')
          })
      )
      .subscribe(result => console.log('Filter results:', result))

My console.error return my array but when I console.log in my subscribe I have undefined. Can you help me ?

Upvotes: 0

Views: 339

Answers (2)

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

Although I would prefer @Bear Nithi's solution, I'll show you the bug in your code. Well, you should return arr.filter(r => r.name == 'x') in your map() call, like this:

this.projects
      .pipe(
          map(arr => {
              console.error(arr);
              return arr.filter(r => r.name == 'x') // here, return filtered array
          })
      )
      .subscribe(result => console.log('Filter results:', result))

Upvotes: 5

Nithya Rajan
Nithya Rajan

Reputation: 4884

Instead of using Array.filter method, you should use buit-in filter operator in rxjs

this.projects
      .pipe(
         filter(r => r.name == 'x')
      )
      .subscribe(result => console.log('Filter results:', result))

Upvotes: 5

Related Questions