TransWikia.com

How to turn an observable of an array into an array of observables (RxJS)

Stack Overflow Asked by Thorsten Westheider on January 7, 2021

Seems people only ever have trouble turning an array of observables into an observable of an array – not the other way round.

So, given an observable

 Observable<Result[]>

how do I go from

Observable<Result[]> to Observable<Result>[] ?

The problem stems from the fact that I got an observable of items

items$: Observable<Item[]>

with

Item: {
   value: number,
   ...
};

where value can take discrete values, say

values = [1, 2, 3]

I need to create an observable for each value, as each feeds a different component.

So I went ahead and did the following mapping

items$.map(items => values.map(value => 
   ({ value, items: items.filter(item => item.value === value) }))

which yields an

 Observable<{ value: number, items: Item[] }[]>

However, in order to assign each value to its component I need

 Observable<{ value: number, items: Item[] }>[]

How do I get there?

One Answer

Just a small change in your code:

values.map(value =>
  items$.map(items => 
    ({ value, items: items.filter(item => item.value === value) })
  )
)

map operator actually creates a new observable

Correct answer by Bogdan Savluk on January 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP