user2093576
user2093576

Reputation: 3092

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

Upvotes: 0

Views: 122

Answers (3)

ppoliani
ppoliani

Reputation: 4906

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

Upvotes: 1

mohlman3
mohlman3

Reputation: 311

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

Upvotes: 1

ncabral
ncabral

Reputation: 2522

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]))
}

Upvotes: 2

Related Questions