Answer the question
In order to leave comments, you need to log in
How to map json to an array of objects?
Good day!
I am writing a small application and I need to map json containing an array of objects into an array of objects. In Java, this is handled through ModelMapper, MapStruct, etc. But I don’t know how to implement this in ts / js.
json comes in response to a post request made via axios.
let routingRequest: RoutingRequest = new RoutingRequest(coordinates);
axios({
method: 'post',
url: routingUrl,
data: routingRequest,
headers: {
'Content-Type': 'application/json'
}
}).then(function (response: AxiosResponse) {
let routes: Route[] = [];
response.data.forEach(
(route: any) => {
routes.push(route as Route)
}
)
}).catch(function (error: AxiosError) {
console.log(error);
});
[
{
"instructions": [
{
"turnDescription": "Продолжите движение",
"distance": 130.26291709756794,
"time": 23447,
"sign": 0,
"name": "",
"points": [
{
"latitude": 53.901085505509265,
"longitude": 27.55511741648531
},
{
"latitude": 53.9010582,
"longitude": 27.5552493
},
{
"latitude": 53.9013356,
"longitude": 27.556052
}]
}],
"description": [],
"distance": 2887.358604882371,
"ascend": 0.0,
"descend": 0.0,
"routeWeight": 506.1757242634384,
"time": 304025,
"pointsOrder": []
}
]
export class Route {
private instructions: Instruction[];
private description: number[];
private distance: number;
private ascend: number;
private descend: number;
private routeWeight: number;
private time: number;
private pointsOrder: number[];
// constructors, getters, setters
}
export class Instruction {
private turnDescription: string;
private distance: number;
private time: number;
private sign: number;
private name: string;
private points: Point[];
// constructors, getters, setters
}
export class Point {
private latitude: number;
private longitude: number;
// constructors, getters, setters
}
e is undefined
, or just undefined
Answer the question
In order to leave comments, you need to log in
Just:
let routes = await axios(...)
.then((response: AxiosResponse<Route[]>) => response.data)
.catch(console.log);
It makes no sense to drive from empty to empty. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question