简体   繁体   中英

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?

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)
);

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