Get value from array of objects as RxJS observable


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?

Source: JavaSript – Stack Overflow

November 23, 2021
Category : News
Tags: angular | arrays | javascript | rxjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.