2013-06-30 127 views
0

我正在使用AngularJS构建应用程序,我正试图在Google地图上绘制位置。我有一个JSON响应,看起来像这样:在javascript中解析JSON响应

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

该指令我使用(angular-google-maps)要求的标志是在下面的格式。我想要做的是创建一个只包含lat和lng值的新数组,看起来像这样。我还需要将纬度和经度重命名为经度和纬度:

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

我新的节目,尤其是在JavaScript。我试图看看是否可以访问JSON响应中的latlng对象,但未定义。这是什么样的:

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

在此先感谢!

+0

最好是迭代指数,而不是钥匙,如果你有一个_Array_。 'var i,latlng; for(i = 0; i <$ scope.locations.length; ++ i){latlng = $ scope.locations [i];/* etc * /}' –

回答

1

$scope.locations[latlng]可让您找到包含latlng键的对象,而不是该键引用的对象。由于迭代变量是索引到数组,你会发现它不易混淆使用反映该名称,例如,i代替latlng

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

在大多数JavaScript实现,你有另一种选择:

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

(还要注意@ rtcherry的评论。)

+1

我会建议使用'angular.forEach'或像[下划线](http://underscorejs.org)或[lodash](http://lodash.com/)这样的库来提供实用功能,如'forEach'。 'Array.forEach'是在JavaScript 1.6中引入的,一些传统浏览器不支持。例如:'angular.forEach($ scope.locations,function(location){...});' – rtcherry