Reputation: 61
I need to filter an Observable and "pass" only the stream, that have specific property value in array of objects, that is inside this stream.
Let's take an example. This is Observable.
const observable = of({name: 'agency', year: '2010', job: [
{name: 'plumber', city: 'Los Angeles'},
{name: 'driver', city: 'Dallas'}
]});
observable.subscribe(response => console.log(response));
I need to console.log a response (response has to be whole stream) in subscribe method only when there is a 'name: plumber' in job array.
So what I do is:
observable.pipe(
filter(obs => obs.job.filter(item => item.name === 'plumber')))
.subscribe(response => console.log(response));
or
observable.pipe(
map(obs => obs.job),
filter(item => item.name === 'plumber'))
.subscribe(response => console.log(response));
Unfortunately, above pieces of code doesn't work as expected.
I want to receive whole stream only if in the job array there is a key-value = name: 'plumber'.
If this condition is met I want to get console.log: {name: 'agency', year: '2010', job: Array(2)}, otherwise nothing should appear in console.
Could you help me?
Upvotes: 0
Views: 79
Reputation: 11934
I think this would do the job:
const observable = of({name: 'agency', year: '2010', job: [
{name: 'plumber', city: 'Los Angeles'},
{name: 'driver', city: 'Dallas'}
]})
.pipe(filter(obj => obj.job.some(({ name }) => name === 'plumber')))
observable.subscribe(response => console.log(response));
For each emitted value, you verify if the jobs
property contains an element that meets the condition in question. This can be achieved by using Array.prototype.some().
Upvotes: 4