在AngularJS中列出JSON数据中的唯一值

时间:2017-08-17 15:09:52

标签: 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只显示一次。

1 个答案:

答案 0 :(得分:2)

您可以获得一系列独特类别:

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