我下面有这个json,如果有更多国家和奖牌的更多对象,那么最好的角度来匹配赢得特定国家的奖牌会是什么?
[
{
"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 :(得分: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>