2017-08-17 45 views
1

比方說,我有一組產品的JSON數據。每個產品都有一個分配給它的類別。我怎麼能列出所有的類別,但只顯示每個類別一次。這是我目前有列出了所有類別,包括重複:在AngularJS中列出JSON數據中的唯一值

(function() { 
 
    var app = angular.module('store', []); 
 
    app.controller('StoreController', ['$scope', function($scope) { 
 
     var vm = this; 
 
     
 
     $scope.products = [{ 
 
     "category": "Cat1", 
 
     "name": "Product1" 
 
     }, { 
 
     "category": "Cat1", 
 
     "name": "Product2" 
 
     }, { 
 
     "category": "Cat2", 
 
     "name": "Product3" 
 
     }, { 
 
     "category": "Cat3", 
 
     "name": "Product4" 
 
     }] 
 
    }]); 
 
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<html lang="en" ng-app="store"> 
 
<body ng-controller="StoreController as vm"> 
 
<div ng-repeat="product in products" class="category"> 
 
    <button>{{product.category}}</button> 
 
</div> 
 
</body> 
 
</html>

所以我想Cat1只顯示一次。

回答

2

你可以得到獨特的類別列表,如:

$scope.uniqueCategories = Object.keys($scope.products.reduce(function(categoryMap, product) { 
    categoryMap[product.category] = 1; 
    return categoryMap; 
}, {})); //["Cat1", "Cat2", "Cat3"] 
+0

這是一個好主意......有評論! – Aaron

相關問題