I'm very new to observables, this might be a silly question for others but I can't find a way to do it. How do I convert
Observable<Array<T>>
where T
is a TypeScript class with property Id(string)
into an Array<string>
? I want to convert the Id
properties into a string array.
Asked
Active
Viewed 137 times
3

Madara's Ghost
- 172,118
- 50
- 264
- 308

user2278488
- 43
- 4
-
Can you refer to this [**answer**](https://stackoverflow.com/questions/44467336/how-can-i-get-an-observer-of-an-input-value-in-child-component/44467942#44467942) – Aravind Aug 04 '17 at 13:20
-
did you have a look to the `map` operator? – Hitmands Aug 04 '17 at 13:22
-
@Aravind thanks for the suggestion but I don't think that answers my question, though I'm getting some ideas from that. – user2278488 Aug 04 '17 at 13:38
-
Yes. That's why I referred you to that answer. can you update the code to the post – Aravind Aug 04 '17 at 13:39
-
@Hitmands yes I'm currently looking into the map function but the concept is about array and not observable array or I'm completely missing something. The implementation should be like the map function I just can't figure it out yet since I'm also new to it. Pure c# dev here before :) – user2278488 Aug 04 '17 at 13:40
-
past relevant code with what you expect and what did you try, otherwise this question will be closed as unclear. – Hitmands Aug 04 '17 at 13:42
2 Answers
1
You are trying to do 2 things here:
- Flatten all arrays from the source array into a single observable of
T
- Map each instance of
T
toId
property
You can use mergeAll
to flatten the observable as you would use reduce
on a normal JS array.
const source = Rx.Observable.of(
[{ Id: '1' }, { Id: '2' }],
[{ Id: '3' }, { Id: '4' }]
);
const flattened = source.mergeAll();
flattened.subscribe(s => console.log(s));
// => {Id:'1'}, {Id:'2'}, {Id:'3'}, {Id:'4'}
You can then use map
(as with a normal JS array) to extract the Id
property
const mapped = flattened.map(s => s.Id);
mapped.subscribe(s => console.log(s))
// => '1', '2', '3', '4'
Pull it all into 1 statement and...
source
.mergeAll()
.map(s => s.Id)
.subscribe(s => console.log(s))
// => '1', '2', '3', '4'

Steve Greatrex
- 15,789
- 5
- 59
- 73
0
You can use reduce operator that like on javascript array. RxJS reduce operator will operate on the whole stream when it is completed.
See the example:
let data$ = new Rx.Subject();
data$
.reduce((acc, el) => {acc.push(...el); return acc;}, [])
.subscribe(x=>console.log(x));
data$.next([{id:'1'}, {id:'2'}]);
data$.next([{id:'3'}, {id:'4'}]);
data$.complete();

Julia Passynkova
- 17,256
- 6
- 33
- 32