How to make ng-repeat filter out duplicate results

前端 未结 16 2931
鱼传尺愫
鱼传尺愫 2020-11-22 06:52

I\'m running a simple ng-repeat over a JSON file and want to get category names. There are about 100 objects, each belonging to a category - but there are only

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 07:30

    If you want to get unique data based on the nested key:

    app.filter('unique', function() {
            return function(collection, primaryKey, secondaryKey) { //optional secondary key
              var output = [], 
                  keys = [];
    
              angular.forEach(collection, function(item) {
                    var key;
                    secondaryKey === undefined ? key = item[primaryKey] : key = item[primaryKey][secondaryKey];
    
                    if(keys.indexOf(key) === -1) {
                      keys.push(key);
                      output.push(item);
                    }
              });
    
              return output;
            };
        });
    

    Call it like this :

提交回复
热议问题