codejunkie codejunkie - 1 month ago 8
JSON Question

Use a JSON object as a value in another JSON object discarding labels

I am trying to store the following JSON object

selection = [ [ { lat: 45.5487853626087, lng: -122.67692568479107 },
{ lat: 45.51511515270127, lng: -122.63298037229107 },
{ lat: 45.532914775094774, lng: -122.60070803342389 },
{ lat: 45.57138119289546, lng: -122.63092043576764 },
{ lat: 45.5785907152446, lng: -122.67967226682232 },
{ lat: 45.55936326549193, lng: -122.69752505002545 },
{ lat: 45.5487853626087, lng: -122.67967226682232 } ] ]


in another object

mySelection = { type: 'Polygon', coordinates: selection};


How can I remove the labels "lat:" and "lng:" as well as "{" and "}"?

The desired result is -

mySelection = { type: 'Polygon', coordinates:
[[45.5487853626087, -122.67692568479107] ,
[45.51511515270127, -122.63298037229107] ,
[45.532914775094774, -122.60070803342389] ,
[45.57138119289546, -122.63092043576764] ,
[45.5785907152446, -122.67967226682232] ,
[45.55936326549193, -122.69752505002545] ,
[45.5487853626087, -122.67967226682232]]
}


The selection values will be different every time. Please help. I am a newbie.

Answer

Generate the array using Array#map method.

var selection =    [ [ { lat: 45.5487853626087, lng: -122.67692568479107 },
        { lat: 45.51511515270127, lng: -122.63298037229107 },
        { lat: 45.532914775094774, lng: -122.60070803342389 },
        { lat: 45.57138119289546, lng: -122.63092043576764 },
        { lat: 45.5785907152446, lng: -122.67967226682232 },
        { lat: 45.55936326549193, lng: -122.69752505002545 },
        { lat: 45.5487853626087, lng: -122.67967226682232 } ] ];

mySelection = {
  type: 'Polygon',
  coordinates: selection[0].map(function(v) {
    return [v.lat, v.lng]
  })
};

console.log(mySelection)

Comments