简体   繁体   中英

Parsing Json Array Object in specific format in javascript

My JSON is:

var json = '{"name":"GeoFence","coordinate":[[1,2],[3,4],[5,6]]}',
obj = JSON.parse(json);
alert(obj.coordinate);

But i need to set the values of coordinates as follows:

var myTrip=[new google.maps.LatLng(1,2),new google.maps.LatLng(3,4),new google.maps.LatLng(5,6)];

Traverse the coordinates and create a new object for each, and add that to myTrip :

var myTrip = [];

for(var i=0; i < obj.coordinate.length; i++) {
    myTrip.push(new google.maps.LatLng(obj.coordinate[i][0],obj.coordinate[i][1]))
}

How about this:

var json = '{"name":"GeoFence","coordinate":[[1,2],[3,4],[5,6]]}',
var obj = JSON.parse(json);
var myTrip = [];
for (var i = 0; i < obj.coordinate.length; i++) {
    myTrip[i] = new google.maps.LatLng(obj.coordinate[i][0], obj.coordinate[i][1]);
}

You need to iterate over the collection of the coordinates:

var myTrip = getCoordinate ();

var getCoordinate = function(){
        var ret = [];

        for(var i = 0, length = coordinate.length; i < length; i++){
           ret.push(new google.maps.LatLng(coordinate[i][0], coordinate[i][1]))
        }

       return ret;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM