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()
);
}
CodePudding user response:
you have multiple options:
- using for ... in
map(response => {
const result = [];
for(const key in response) {
result.push({key, carName: response[key]});
}
return result;
}),
- using Object.keys() with Array.prototype.map():
map(response => Object.key(response).map(key => ({key, carName: response[key] }))});
CodePudding user response:
Hi its not an array its object so you need to loop this manually
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
you need to do like this