1

I have an array of objects myData$ which is an BevahiorSubject (from the RxJS library). myData$ looks like this:

[
  {
    type: 'car',
    year: 12,
  },
  {
    type: 'boat',
    year: 9,
  },
]

I want to assign the value from the year-key of the object that contains the string-value 'car' at the type-key to my other Observable desiredYear$, but it should directly get the value without being stored in an array. So desiredYear$ should equal 12, not [12].

First step, I tried getting the right object by filtering for 'car'-string:

this.desiredYear$ = this.myData$.pipe(
  map(
    myData => myData.filter(data => data.type === 'car'),
  ),
);

It returns the object of the desired value but not yet the desired value of year-key, and the result (see below) is stored in an array (which I don't want):

[
    {
        type: 'car',
        year: 12,
    },
]

What can I do go get directly 12 returned?

1 Answer 1

3

I'd say better fit is to use Array#find instead of Array#filter and access the year property directly

this.desiredYear$ = this.myData$.pipe(
  map(
    myData => myData.find(data => data.type === 'car')?.year,
  ),
);

The optional chaining ?. operator would mitigate errors if the Array#find returns undefined. Which it would if there is no element in array satisfying the condition data.type === 'car'.

Note that in such a case, the desiredYear$ observable would emit undefined. If you wish to ignore the undefined emissions, you could pipe in filter operator

this.desiredYear$ = this.myData$.pipe(
  map(
    myData => myData.find(data => data.type === 'car')?.year,
  ),
  filter(year => !!year)
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.