Observable transformation
I'm very new to observables, this might be a silly question for others, but I can't seem to find a way to do this. How to convert
Observable<Array<T>>
where T
is a TypeScript class with a property Id(string)
to Array<string>
? I want to convert properties Id
to an array of strings.
source to share
You are trying to do 2 things here:
- Flatten all arrays from the original array into one observable
T
- Match each instance of the property
T
toId
You can use mergeAll
to flatten the observable as you would use reduce
in 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'}
Then you can use map
(as with a normal JS array) to retrieve the propertyId
const mapped = flattened.map(s => s.Id);
mapped.subscribe(s => console.log(s))
// => '1', '2', '3', '4'
Pull it all into 1 operator and ...
source
.mergeAll()
.map(s => s.Id)
.subscribe(s => console.log(s))
// => '1', '2', '3', '4'
source to share
You can use the reduction operator similar to javascript array. The RxJS abbreviation operator will run on the entire thread when completed.
See 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();
source to share