使用 RxJS 和 observable 从请求映射键值对

Mapping Key Value Pair from request using RxJS and observable

我的 API 端点 returns json 作为键值对结果。如何将此集合映射到 .pipe 方法中的对象 ICar。我需要可观察的,因为我想缓存结果。

示例 json 结果:

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

我的示例代码:

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()
      );
}

嗨,它不是一个数组,它的对象,所以你需要手动循环这个

    for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

你需要这样做

您有多种选择:

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] }))});