Home > Blockchain >  Convert {number, Observable<string>} to Observable<number, string>
Convert {number, Observable<string>} to Observable<number, string>

Time:10-30

I want to transform an array of objects of type

{
  id: number,
  data: Observable<string>
}

to an array of objects of type

Observable<{id: number, data: string}>

only using RxJS operators if possible.

CodePudding user response:

If i understood correctly, this should be it:

const subject = new Subject<string>();

// Dummy array
const array = [
  {
    id: 1,
    data: of("smthing")
  }, {
    id: 2,
    data: of("smthingelse")
  }, {
    id: 3,
    data: subject.asObservable()
  }
]
// Function that maps {id: number, data: Observable<string>} into Observable<{id: number, data: string}>
const mapTo = (array) => array.map(item => item.data.pipe(map(data => ({...item, data}))));

const mappedArray = mapTo(array);
  • Related