Home > Mobile >  How can I convert an array of arrays into an array of objects
How can I convert an array of arrays into an array of objects

Time:05-13

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);

CodePudding user response:

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);

CodePudding user response:

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)

CodePudding user response:

Use a JSON.parse reviver for a one pass solution

Since MapBox returns a route as json one could automatically convert all coordinate properties using a JSON.parse reviver parameter.

The snippet simulates MapBox route query and parses the json string using a reviver. This reviver watches for properties named "coordinates" (there is more than one) and converts these to a geolocation object: {longitude,latitude}.

Also see: how to use reviver function with fetch.response.json()?

// simulate MapBox data fetch returning json route data
let json = document.getElementById("mapdata").textContent;

  let data = JSON.parse(json, (key,val) => 
    key === "coordinates" ? val.map(p => ({ longitude: p[0], latitude: p[1] })) : val 
  );

console.log("coordinates:", data.routes[0].legs[0].steps[0].geometry.coordinates);
<pre><code id="stdout"></code></pre>

<!-- Example MapBox Route Data for Berlin, DE -->
<script id="mapdata" type="text/template">
{"routes":[{"country_crossed":false,"weight_name":"auto","weight":37.64,"duration":31.687,"distance":132,"legs":[{"via_waypoints":[],"admins":[{"iso_3166_1_alpha3":"DEU","iso_3166_1":"DE"}],"weight":37.64,"duration":31.687,"steps":[{"intersections":[{"entry":[true],"bearings":[264],"duration":28.8,"mapbox_streets_v8":{"class":"tertiary"},"is_urban":true,"admin_index":0,"out":0,"weight":32.4,"geometry_index":0,"location":[13.39111,52.51488]},{"bearings":[85,173,264,353],"entry":[false,false,true,false],"in":0,"turn_weight":2,"turn_duration":0.007,"mapbox_streets_v8":{"class":"tertiary"},"is_urban":true,"admin_index":0,"out":2,"geometry_index":6,"location":[13.389354,52.514774]}],"maneuver":{"type":"depart","instruction":"Drive west on Französische Straße.","bearing_after":264,"bearing_before":0,"location":[13.39111,52.51488]},"name":"Französische Straße","duration":31.687,"distance":132,"driving_side":"right","weight":37.64,"mode":"driving","geometry":{"coordinates":[[13.39111,52.51488],[13.390935,52.514869],[13.390867,52.514865],[13.389913,52.514804],[13.389685,52.514793],[13.389399,52.514776],[13.389354,52.514774],[13.38918,52.514763]],"type":"LineString"}},{"intersections":[{"bearings":[84],"entry":[true],"in":0,"admin_index":0,"geometry_index":7,"location":[13.38918,52.514763]}],"maneuver":{"type":"arrive","instruction":"You have arrived at your destination.","bearing_after":0,"bearing_before":264,"location":[13.38918,52.514763]},"name":"Französische Straße","duration":0,"distance":0,"driving_side":"right","weight":0,"mode":"driving","geometry":{"coordinates":[[13.38918,52.514763],[13.38918,52.514763]],"type":"LineString"}}],"distance":132,"summary":"Französische Straße"}],"geometry":{"coordinates":[[13.39111,52.51488],[13.38918,52.514763]],"type":"LineString"}}],"waypoints":[{"distance":1.133,"name":"Französische Straße","location":[13.39111,52.51488]},{"distance":1.509,"name":"Französische Straße","location":[13.38918,52.514763]}],"code":"Ok","uuid":"pGaxnG16PD50dy9eyc0XlupTDC-ehwMono8FhUXUKjmEKnJ7uLSazw=="}
</script>

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

i'm not 100% sure if this is an object tbh :)

It's an array of objects.

You can use several Array (extension) methods to produce such an array. Here's a snippet using reduce, map and forEach. See

const latLongs = [
  [ 52.25155727661456, 6.148788223460181 ],
  [ 52.25179372912126, 6.147507915253847 ],
  [ 52.25205645297342, 6.147157440051708 ],
  [ 52.25237609814013, 6.147178897723827 ],
];

// reduce
const latLongsReduced = latLongs.reduce( (acc, [latitude, longitude]) => 
  [...acc, {latitude, longitude} ], []);

// map
const latLongsMapped = latLongs.map( ([latitude, longitude]) => 
  ({latitude, longitude}) );
  
// forEach
let latLongsEach = [];
latLongs.forEach( ([latitude, longitude]) => 
  latLongsEach.push({latitude, longitude}) );

console.log(latLongsReduced);
console.log(latLongsMapped);
console.log(latLongsEach);
.as-console-wrapper {
    max-height: 100% !important;
}

  • Related