user1415633 user1415633 - 3 months ago 27
Javascript Question

The JSON structure with Javascript

I have a JSON file with next structure :

{"coordinates":
[[3.562251301440316,-76.2809944152832],
[3.54117750673122,-76.28803253173828],
[3.5488874874187673,-76.31258010864258],
[3.5643072556238033,-76.3139533996582],
[3.569104464176614,-76.29936218261719],
[3.565335230992449,-76.2894058227539],
[3.562593960789916,-76.28219604492188]]
}


The correct structure is :

{
"u1": {"a":3.5649925726638965, "o":-76.32013320922852},
"u2": {"a":3.5432335078647568, "o":-76.30863189697266},
"u3": {"a":3.5581393792979417, "o":-76.2835693359375},
"u4": {"a":3.571503059060428, "o":-76.29026412963867},
"u5": {"a":3.5774995188413183, "o":-76.3081169128418},
"u6": {"a":3.5804120708676126, "o":-76.32476806640625}
}


question:
What change I must make for work with the following code javascript with the first coordinates?

I have ready the second coordinate file and your function is ok, but I must many changes manually.

the Javascript code for work with this coordinates is

function initialize()
{
var hr = new XMLHttpRequest();
hr.open("GET", "mylist.json", true);
hr.setRequestHeader("Content-type", "application/json", true);

var la, lo ;

hr.onreadystatechange = function()
{
var map = new google.maps.Map(document.getElementById('mapa'), {
zoom: 12,
center: new google.maps.LatLng(3.555, -76.29),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var pathCoordinates = new google.maps.MVCArray();
var arr = [];

if(hr.readyState == 4 && hr.status == 200)
{
var data = JSON.parse(hr.responseText);
for(var obj in data)
{
la = data[obj].a;
lo = data[obj].o;
marker = new google.maps.Marker({
position: new google.maps.LatLng( la , lo),
map: map});
}
}
}
hr.send(null);
}

Answer

You can use the map/reduce function to parse your object:

var coords = {
  "coordinates": [
    [3.562251301440316, -76.2809944152832],
    [3.54117750673122, -76.28803253173828],
    [3.5488874874187673, -76.31258010864258],
    [3.5643072556238033, -76.3139533996582],
    [3.569104464176614, -76.29936218261719],
    [3.565335230992449, -76.2894058227539],
    [3.562593960789916, -76.28219604492188]
  ]
}

var obj = coords.coordinates.map(function(item, idx) {
  return {
    "a": item[0],
    "o": item[1]
  }
}).reduce(function(previousValue, currentValue, index, vector){
    previousValue["u" + (index+1)] = currentValue
    return previousValue;
}, {});

console.log(obj)