简体   繁体   中英

Parse JSON response in javascript

I'm building an app using AngularJS and I am trying to plot locations on a google map. I have a JSON response that looks like this:

 locations: [{ 
    id: 123
    latlng:  { 
        lat: 56.3
        lon: -2.1
        } 
    name: TestName
    }]

The directive I'm using ( angular-google-maps ) requires the markers to be in the below format. What I would like to do is to create a new array containing only the lat and lng values, that looks like this. I also need to rename the lat and lng to longitude and latitude:

markers: [ {
        latitude: 45,
        longitude: -74
    },{
        latitude: 46,
        longitude: -75  
    }]

I'm new to programming, especially in javascript. I tried to see if I can access the latlng object in the JSON response, but get undefined. Here is what that looks like:

for (var latlng in $scope.locations) {
        if ($scope.locations.hasOwnProperty(latlng))
        {
            var latitude = $scope.locations[latlng].lat;
        }
        console.log(latitude);
    }

Thanks in advance!

$scope.locations[latlng] gets you to the object containing the latlng key, not the object referred to by that key. Since the iteration variable is an index into the array, you'll find it less confusing to use a name that reflects this, eg, i instead of latlng :

for (var i in $scope.locations) {
    …
    var latitude = $scope.locations[i].latlng.lat;
    …
}

In most JavaScript implementations, you have another option:

$scope.locations.forEach(function(location) {
    …
    var latitude = location.latlng.lat;
    …
});

(Also note @rtcherry's comment.)

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