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);
You can use map and destructuring to turn the subarrays to objects:
let coordinates = [
[52.25155727661456, 6.148788223460181],
[52.25179372912126, 6.147507915253847],
[52.25205645297342, 6.147157440051708],
[52.25237609814013, 6.147178897723827]
];
let result = coordinates.map(([longitude, latitude]) => ({longitude, latitude}));
console.log(result);
Use map to return a array of object
const coords = [
[31.00283837, -5.3838382],
[2.52346457, 8.23472645]
];
const jsonCoords = coords.map(coord => ({
latitude: coord[0],
longitude: coord[1]
}))
console.log(jsonCoords)
With for loop:
let cords = [
[6.148788223460181, 52.25155727661456],
[8.148788223460181, 12.25155727661456],
[3.148788223460181, 16.25155727661456],
[8.148788223460181, 17.25155727661456],
]
let jsonObj = [];
for(let i = 0; i < cords.length; i ++) {
jsonObj.push({
latitude: cords[i][1],
longitude: cords[i][0]
})
}
console.log(jsonObj)