Suppose I had an api that returns the following JSON structure:
{
"Response": {
"status": {
"code": "SUCCESS",
"message": "owner found",
"count": "1"
},
"owners": [
{
"ownerId": "12345",
"name": "Example Person",
"cars": [
{
"make": "Toyota"
"year": "2004"
"model": "Camry"
}
]
}
]
}
}
I want to map this json structure into these typescript models:
export class ApiResponse{
constructor(
public status: Status,
public owners: Owner[]
) {}
}
export class Status {
constructor(
public code: string,
public message: string,
public count: number
) {}
}
export class Owner{
constructor(
public ownerId: number,
public name: string,
public cars: Car[]
) {}
}
export class Car{
constructor(
public make: string;
public year: string;
public model: string;
)
}
From my understanding of angular 7, you can use pipe and map from rxjs to achieve this:
this.http.get(url).pipe(
map((data: any[]) => data.map((item: any) => new ApiResponse(
new Status(
item.status.code,
item.status.message,
item.status.count),
...
Using this I am able to map a JSON object, but I am unsure how to approach mapping arrays and nested arrays.
How should I approach mapping a JSON with nested arrays?
Observableto the component for rendering.