The jquery loop on an object returns Uncaught TypeError: Unable to read the 'lat' property of undefined

advertisements

Hi I have a json object which is returned as follows;

{
  "status": "ok",
  "data": {
    "mapdata": [
      {
        "name": "Test title",
        "description": "Lorem ipsum dolor sit amet",
        "lat": "51.297387",
        "lng": "-0.737240"
      }
      {
        "name": "Example Event 5",
        "description": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget tincidunt turpis. Nam tincidunt non diam eu mollis. Suspendisse lobortis rhoncus ante at auctor.&nbsp;</p>\r\n",
        "lat": "51.5232032",
        "lng": "-0.6053448999999773"
      }
    ]
  }
}

I want to loop over the the data array but I'm not sure how, this is the code I have so far:

 $.ajax({
    url: '/googlemaps',
    type: 'POST',
    dataType: 'json',
    success: function (response) {
        for (var key in response.data) {
            console.log(key.name);
            var latLng = new google.maps.LatLng(key.lat, key.lng);

            // Creating a marker and putting it on the map
            var marker = new google.maps.Marker({
                position: latLng,
                map: map,
                title: data.name
            });
            //send details to infoBox function to create infoWindow
            infoBox(map, marker, data);
        } // end for

    } //end success
})

However the when I loop over the keys and try to pass the lat and lng to the google maps function it outputs this error:

Uncaught TypeError: Cannot read property 'lat' of undefined

and the console.log is undefined for console.log(key.name);. Any ideas what I am doing wrong and how I can loop through the mapdata array?


You are trying to loop through an object(response.data) instead of the array (response.data.mapdata). Also, I used the normal for loop for it. So I believe this should work:

for(var i = 0; i < object.data.mapdata.length; i++) {
    console.log(object.data.mapdata[i].name);
    var latLng = new google.maps.LatLng(object.data.mapdata[i].lat, object.data.mapdata[i].lng);

    // Creating a marker and putting it on the map
    var marker = new google.maps.Marker({
        position: latLng,
        map: map,
        title: object.data.mapdata[i].name
    });
    //send details to infoBox function to create infoWindow
    infoBox(map, marker, data);
} // end for