Javascript 如何在angularjs中输出对象数组?

Javascript 如何在angularjs中输出对象数组?,javascript,angularjs,Javascript,Angularjs,我有一个像这样的对象: $scope.locations [ {Kanaanbadet: {"name":"Kanaanbadet","image":"http://www.stockholm.se/Web/Core/Pages/Special/StreamServiceGuideImage.aspx?path=%2fWeb%2fCore%2fPages%2fSpecial%2fServiceGuideFile.aspx%3ffileid%3d14b313cb2b2f45e380

我有一个像这样的对象:

$scope.locations    [

    {Kanaanbadet: {"name":"Kanaanbadet","image":"http://www.stockholm.se/Web/Core/Pages/Special/StreamServiceGuideImage.aspx?path=%2fWeb%2fCore%2fPages%2fSpecial%2fServiceGuideFile.aspx%3ffileid%3d14b313cb2b2f45e380eb88156c95b539","_cached_page_id":"4b71e342c82be9de1c74de3c2f57ea1c4dde8150","long":"17.85448","lat":"59.34966","url":"http://www.stockholm.se/-/Serviceenhetsdetaljer/?enhet=cf0a856830e4422cb55dcd60e8e6b40b"}},
    {Johannelundsbadet:{"name":"Johannelundsbadet","image":"http://www.stockholm.se/Web/Core/Pages/Special/StreamServiceGuideImage.aspx?path=%2fWeb%2fCore%2fPages%2fSpecial%2fServiceGuideFile.aspx%3ffileid%3d3e4c2056b5534cfc9b0799e2377b8ce4","_cached_page_id":"18cf34222d74612979afd945a925abc0bf16e44d","long":"17.98914","lat":"59.34098","url":"http://www.stockholm.se/-/Serviceenhetsdetaljer/?enhet=ebf8d49780224e908064551c35dbcca4"}},
    ...more items
]
我会在foreach中的模板中列出名称,并且我希望能够引用密钥

<a  ng-href="#/{{location}}" class="location" ng-repeat="location in locations">{{location}}</a>


我可以改变数组,使其看起来像其他方式,但我希望将其保留为一个数组,这样我就可以对其进行排序,并以某种方式从对象键中选择项目。我的阵列应该如何构造?

我想您应该将其分为两个重复:

  <div ng-controller="DemoCtrl">
    <div ng-repeat="location in locations">
      <a ng-href="#/{{item.url}}" class="location" ng-repeat="item in location">{{item.name}}</a>
    </div>
  </div>


也许检查一下这个

老实说,我真的不喜欢你构建对象的方式。对象应该是匿名的,并且名称应该是其中的一个属性。这样,您就可以使用
location.name

综上所述,您可以使用
Object.keys()
获取对象中的键数组

<a ng-href="getKey(location)" 
   class="location" 
   ng-repeat="location in locations"> {{ getKey(location) }}
</a>


注意:根据所需的浏览器支持,您最好使用
for(key-in-location)
循环遍历属性,就像一些较旧的浏览器
Object.keys()

您可以只做
{location.name}
吗?位置是数组,更新问题。
@wayne,这将适用于具有键值的对象,key输出数组key(integer)不,您可以这样获得key。您可以将阵列的一半构造为数据存储。另一半作为对象。但我真的不喜欢这样。另一种方法是使用对象的纯数组作为数据存储,并使用lodash
\ where
查找和选择特定项。
 $scope.getKey = function(location){
    return Object.keys(location)[0];
 }