0

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?

2
  • So what exactly should be the expected result? Commented Sep 19, 2019 at 20:31
  • The expected result should be the whole Observable object: {name: 'agency', year: '2010', job: Array(2)}, but only if there is name: 'plumber' condition met.
    – Kamil P.
    Commented Sep 19, 2019 at 20:35

1 Answer 1

4

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

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.