-2

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:

[1

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: enter image description here

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);
hasbullah
  • 45
  • 5
  • Does this answer your question? [Convert Array to Object](https://stackoverflow.com/questions/4215737/convert-array-to-object) – Kim Skovhus Andersen May 12 '22 at 12:30
  • [Please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551) – Ivar May 12 '22 at 12:32
  • @Kim, that indeed converts an array to an object, but if you read the question a bit closer, they still want an array... So it is not duplicate of that. – trincot May 12 '22 at 12:33
  • 1
    You're misunderstanding what JSON is. JSON is a very specific text format that can be pasted as-is into code and assigned to a variable. But there's no such thing as a "JSON Object". What you have is an array of arrays, and you're trying to turn it into an array of objects. That's fine but not necessary to be able to POST it. You can just stringify the original Array (to get a string of JSON text) and send that to your backend. –  May 12 '22 at 12:33
  • 1
    To me it looks like the question is asking how to turn an array of arrays into an array of objects. The only reference to JSON object is a variable name. – James May 12 '22 at 12:38
  • @James I'm referring to this: `I need to convert this array into an object so that I can send it to the backend with post`. Based on this I assume that OP doesn't understand JSON vs. Object and is pointlessly trying to turn their array into (not an actual) object –  May 12 '22 at 12:42
  • Oh, yeah. Sorry, I was a bit too fast. I see that Array.map is suggested. That should do the trick I suppose :-) – Kim Skovhus Andersen May 12 '22 at 12:43
  • @Chris, as you may well know there are many well known JavaScript libraries that allow to post objects, where serialisation is taken care of. We cannot assume the Asker is misunderstanding the posting process with the little info we get here. They even mention mapbox which has methods for exchanging data objects (see [here](https://docs.mapbox.com/mapbox-gl-js/api/sources/)) – trincot May 12 '22 at 12:46
  • @trincot Well, OP just updated their question with xhr code that clearly shows they're doing a manual POST request. Still, it's perfectly possible that the backend expects an array of lat/lng objects but we can't know either way. The page you link to uses an array of arrays for the coordinates, so I'll stick to my interpretation until I can't. –  May 12 '22 at 12:50
  • Indeed, it is disappointing to see the Asker is actually using the outdated `XMLHttpRequest` object. – trincot May 12 '22 at 12:52
  • OP, in all likelihood the only thing you need is this: `xhr.send(JSON.stringify(originalArrayWhichIsFine));` Because you're currently *not* doing "// send rquest with JSON payload", you're sending `[object Object]` or something like that –  May 12 '22 at 12:55

4 Answers4

2

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);
trincot
  • 317,000
  • 35
  • 244
  • 286
  • You're solving OP's trivial problem (which is a dupe for sure btw) but I don't think that is their actual problem. –  May 12 '22 at 12:37
  • I couldn't find a dupe yet... if you find one, I will support it. – trincot May 12 '22 at 12:38
  • *"the result in your answer is still an array"*: that's what they included in their question as the desired output. They just used poor wording -- and they realised it when they wrote *"i'm not 100% sure if this is an object tbh"*. No need to curse. – trincot May 12 '22 at 13:10
  • "i'm not 100% sure if this is an object tbh" clearly says that they actually want an **object**, not something that is still an array. This is also very much supported by the rest of the question. I'll gladly eat my words if it turns out I'm wrong but I'd wager a year's income I'm goddamn not. –  May 12 '22 at 13:17
1

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)
Harshit Rastogi
  • 1,996
  • 1
  • 10
  • 19
0

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)
Marcin Mąsior
  • 226
  • 1
  • 7
0

Take your starting array and then map it into a new array of objects

const originalArray = [ [6.148788223460181,52.25155727661456] , [6.148788223460181,52.25155727661456] , [6.148788223460181,52.25155727661456] ]
console.log('@array', originalArray)

const newArray = originalArray.map(element => ({latitude: element[1], longitude: element[0]}))
console.log('@newArray',newArray)
raindrop
  • 9
  • 2