简体   繁体   中英

Filter Observable by property of array of objects

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?

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM