I have an array of objects containing coordinates. Currently all the keys are in string format, but in order for the API I'm using to use the coordinates they can't have quotation marks around them.
E.g. I currently have something like:
let route = [{"latitude": 51.6788, "longitude": -0.1689}, {"latitude": 51.8753, "longitude": -0.1693}...]
and I need to get it as
let formattedRoute = [{lat: 51.6788, lng: -0.1689}, {lat: 51.8753, lng: -0.1693}...]
So in VScode (I'm using react native if that also has any effect) I've tried iterating through the array and using JSON.parse on the objects and pushing them to a new array, but when console logging the new array (formattedRoute) it still returns them with the keys in quotation marks. I also tried using JSON.stringify on each object before JSON.parse but nothing changed.
For example:
let route = [{"latitude": 51.6788, "longitude": -0.1689}, {"latitude": 51.8753, "longitude": -0.1693}]
for (let i = 0; i < route.length; i++) {
let coord = {lat: route[i].latitude, lng: route[i].longitude}
coord = JSON.parse(coord)
console.log(coord)
formatRoute.push(coord) //where formatRoute is an array defined outside the for loop
}
returns:
{"lat": 51.50729, "lng": -0.16551}
{"lat": 51.50726, "lng": -0.16549}
etc.
However, when I tried doing this in a fiddle on the MDN website I got what I wanted:
So I'm not really sure why it isn't working in VScode. Am I maybe missing something or have I misunderstood how JSON.parse is supposed to work? Or is this maybe something to do with how react interprets objects - in which case how could I get it into the format I want?
A JS object literal is a key-value structure with no notion of quotes around the keys.
To get your new format you can just do:
const route = [{"latitude": 51.6788, "longitude": -0.1689}, {"latitude": 51.8753, "longitude": -0.1693}];
const newRoute = route.map(({ latitude: lat, longitude: lng }) => ({ lat, lng }));