Michael B
Michael B

Reputation: 343

Filter observable array by object property

I currently have an array of observables which I'm iterating over using an *ngFor loop with the async pipe. I would like to filter the observables by a property value on the object, e.g

Original array:

[{ name: test1,
   type: type1},
 { name: test2,
   type: type2}
 { name: test3,
   type: type1}
 { name: test4,
   type: type2}]

I would like to filter this and make two new observable (arrays), one for type1 and one for type2

I tried obs.filter(x => x.type == "type1) but it returns nothing

I then tried obs.mergeAll().filter(x => x.type == "type1") and I can subscribe to this and log it to the console correctly but now it doesn't work with my *ngFor (async pipe). I'm guessing it's because the mergeAll means it's no longer an observable array? So do I need to convert it back?

Upvotes: 3

Views: 2927

Answers (1)

Kamil Naja
Kamil Naja

Reputation: 6692

You are probably missing pipe operator from RXJS6.

import { of, from } from "rxjs";

import { filter, map } from "rxjs/operators";

const obs = from([{
    name: 'test1',
    type: 'type1'
},
{
    name: 'test2',
    type: 'type2'
},
{
    name: 'test3',
    type: 'type1'
},
{
    name: 'test4',
    type: 'type2'
}]);

const source = obs.pipe(
    filter(data => data.type === 'type2')
)


console.log(source.subscribe(item => console.log(item)));
// prints {name: "test2", type: "type2"}
{name: "test4", type: "type2"}

If you want to get an array:


const items = [];
console.log(source.subscribe(item => items.push(item)));
console.log(items);

Upvotes: 1

Related Questions