How to make ng-repeat filter out duplicate results

前端 未结 16 2953
鱼传尺愫
鱼传尺愫 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:18

    Here's a straightforward and generic example.

    The filter:

    sampleApp.filter('unique', function() {
    
      // Take in the collection and which field
      //   should be unique
      // We assume an array of objects here
      // NOTE: We are skipping any object which
      //   contains a duplicated value for that
      //   particular key.  Make sure this is what
      //   you want!
      return function (arr, targetField) {
    
        var values = [],
            i, 
            unique,
            l = arr.length, 
            results = [],
            obj;
    
        // Iterate over all objects in the array
        // and collect all unique values
        for( i = 0; i < arr.length; i++ ) {
    
          obj = arr[i];
    
          // check for uniqueness
          unique = true;
          for( v = 0; v < values.length; v++ ){
            if( obj[targetField] == values[v] ){
              unique = false;
            }
          }
    
          // If this is indeed unique, add its
          //   value to our values and push
          //   it onto the returned array
          if( unique ){
            values.push( obj[targetField] );
            results.push( obj );
          }
    
        }
        return results;
      };
    })
    

    The markup:

    {{ item.name }}

提交回复
热议问题