Anand
Anand

Reputation: 1671

How to map an Observable to another type of Observable?

I have this

  public getRouteData(): BehaviorSubject<string[]> {
     return this.routeData;
  }

I wan to map this to an Observable of {name: r} where r is an item in the string[]

public gridData: BehaviorSubject<any[]> = new BehaviorSubject([]);

I would like to take the string[] and map to array of object {name: r} where r is item of array, so that I can bind the object array to the grid.

Somehow not able to sequence or the syntax right.

Tried getRouteData().map(r => ({name: r})).subscribe(r => this.gridData.next(r)); but this is not correct as I am ending up with {name:string[]} instead of [{name:string}]

Can anyone please help?

Thanks!

Upvotes: 5

Views: 7769

Answers (1)

Daniel W Strimpel
Daniel W Strimpel

Reputation: 8470

If I'm understanding correctly, I think you are looking for this:

getRouteData() // => Observable<string[]>
    .map(r => r.map(v => ({name: v}))) // => Observable<{ name: string }[]>
    .subscribe(r => this.gridData.next(r));

The outer map(...) is iterating over each value emitted from your observable. So, r is of type string[].

The inner map(...) is iterating over each element in your r array and converting the string to the { name: string } type.

Upvotes: 12

Related Questions