2017-02-21 70 views
-1

我在下面有這個json,如果有更多的對象具有更多的國家和獎牌,那麼角度最好的方法是什麼?在angularJs中匹配來自同一陣列中不同對象的值

[ 
{ 
"athlete": "KOGO, Micah", 
"country": "KEN", 
"sex": "Men", 
"event": "10000m", 
"medal": "Bronze" 
}, 
{ 
"athlete": "BEKELE, Kenenisa", 
"country": "ETH", 
"sex": "Men", 
"event": "10000m", 
"medal": "Gold" 
}, 
{ 
"athlete": "SIHINE, Sileshi", 
"country": "ETH", 
"sex": "Men", 
"event": "10000m", 
"medal": "Silver" 
}, 
{ 
"athlete": "FLANAGAN, Shalane", 
"country": "USA", 
"sex": "Women", 
"event": "10000m", 
"medal": "Bronze" 
} 
] 
+0

什麼是你想要的輸出? –

+0

顯示每個國家的獎牌數和贏得的獎牌 – ronoc4

+1

好的,您希望輸出結構如何?我想你可能能夠提供基於樣本輸入的樣本輸出。 –

回答

2

這創建了一個無序的獎牌清單國家列表。

var app = angular.module("yourApp", []); 
 

 
app.controller("controller", function($scope) { 
 

 
    $scope.input = [{ 
 
     "athlete": "KOGO, Micah", 
 
     "country": "KEN", 
 
     "sex": "Men", 
 
     "event": "10000m", 
 
     "medal": "Bronze" 
 
    }, 
 
    { 
 
     "athlete": "BEKELE, Kenenisa", 
 
     "country": "ETH", 
 
     "sex": "Men", 
 
     "event": "10000m", 
 
     "medal": "Gold" 
 
    }, 
 
    { 
 
     "athlete": "SIHINE, Sileshi", 
 
     "country": "ETH", 
 
     "sex": "Men", 
 
     "event": "10000m", 
 
     "medal": "Silver" 
 
    }, 
 
    { 
 
     "athlete": "FLANAGAN, Shalane", 
 
     "country": "USA", 
 
     "sex": "Women", 
 
     "event": "10000m", 
 
     "medal": "Bronze" 
 
    } 
 
    ]; 
 

 
    $scope.countries = $scope.input.map(function(obj) { 
 
    return obj.country; 
 
    }); 
 

 
    $scope.uniqueCountries = $scope.countries.filter(function(item, pos) { 
 
    return $scope.countries.indexOf(item) == pos; 
 
    }) 
 

 
    $scope.getMedalCount = function(country, colour) { 
 
    var count = 0; 
 
    angular.forEach($scope.input, function(obj) { 
 
     if ((obj.country === country) && (obj.medal === colour)) { 
 
     count++; 
 
     } 
 
    }); 
 
    return count; 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<body ng-app="yourApp"> 
 
    <div ng-controller="controller"> 
 
    <ul> 
 
     <li ng-repeat="country in uniqueCountries"> 
 
     {{ country }} 
 
     <ul> 
 
      <li>Gold: {{ getMedalCount(country, "Gold") }}</li> 
 
      <li>Silver: {{ getMedalCount(country, "Silver") }}</li> 
 
      <li>Bronze: {{ getMedalCount(country, "Bronze") }}</li> 
 
     </ul> 
 
     </li> 
 
    </ul> 
 
    </div> 
 
</body>

相關問題