Search code examples
angularrxjsobservable

Mapping Key Value Pair from request using RxJS and observable


My API endpoint returns json as key-value pair result. How can I map this collection to the object ICar inside .pipe method. I need observable, because I want to cache result.

Example json result:

{"1":"Ford", "2":"Toyota"}

My example code:

export interface ICar {
  key: string;
  carName: string;
}

getCars():Observable<ICar[]> {
   return this.httpClient.get("https://cars.com/cars")
      .pipe(
          map(???),   <--------------dont't know how to map it here
          publishReplay(1), 
          refCount()
      );
}

Solution

  • you have multiple options:

    map(response => {
      const result = [];
      for(const key in response) {
        result.push({key, carName: response[key]});
      }
      return result;
    }),
    
      map(response => Object.key(response).map(key => ({key, carName: response[key] }))});
    

    EDIT

      map(response => Object.entries(response).map(([key, value])=> ({key, carName: value }))});
    

    In the docs it states that there's a difference between for ... in an Object.entries(), but since you use it on plain objects it won't matter.