I working with mapbox where I can draw a route that gives me coordinates that I then put into an array. I need to convert this array of arrays into an array of objects, so that I can send it to the backend with post. But I could figure out how to do this. this is how my array looks like right now with a few coordinates in it:
[
and what I want is something like this, i'm not 100% sure if this is an object tbh :) :
[{
"latitude": 52.25155727661456,
"longitude": 6.148788223460181
}, {
"latitude": 52.25179372912126,
"longitude": 6.147507915253847
}, {
"latitude": 52.25205645297342,
"longitude": 6.147157440051708
}, {
"latitude": 52.25237609814013,
"longitude": 6.147178897723827
}]
How could I convert the array that I have into the above? I need this so I can send this with a post function to a backend API. I tried using something like this:
for (var i = 0, len = coords.length; i < len; i++) {
jsonObj['latitude'] = coords[i];
}
But it didn't work out like how I wanted it to work. This is a little bit of my code where I get the values into my array:
and this is how i'm trying to send my data to the server:
const xhr = new XMLHttpRequest();
// listen for `load` event
xhr.onload = () => {
// print JSON response
if (xhr.status >= 200 && xhr.status < 300) {
// parse JSON
//const response = JSON.parse(xhr.responseText);
console.log(xhr.responseText);
}
};
// open request
xhr.open('POST', saveAllMeasurement);
// set `Content-Type` header
xhr.setRequestHeader('Content-Type', 'application/json');
// send rquest with JSON payload
xhr.send(coordsObj);