programing

중복된 결과를 ng-repeat 필터에서 제외하는 방법

linuxpc 2023. 3. 7. 21:08
반응형

중복된 결과를 ng-repeat 필터에서 제외하는 방법

심플하게 하고 있어요ng-repeatJSON 파일을 사용하여 카테고리 이름을 가져옵니다.각각 카테고리에 속하는 개체는 약 100개이지만 범주는 약 6개뿐입니다.

현재 코드는 다음과 같습니다.

<select ng-model="orderProp" >
  <option ng-repeat="place in places" value="{{place.category}}">{{place.category}}</option>
</select>

출력은 대부분 중복되는 100개의 다른 옵션입니다.Angular를 사용하여 어떻게 해야 합니까?{{place.category}}이미 존재하며, 이미 존재하는 경우 옵션을 생성하지 않습니까?

편집: 내 Javascript에서$scope.places = JSON data알기 쉽게 하기 위해서

Angular의 고유한 필터를 사용할 수 있습니다.UI(여기서 사용 가능한 소스 코드: Angular)UI 고유 필터) 및 ng-options(또는 ng-repeat)에서 직접 사용합니다.

<select ng-model="orderProp" ng-options="place.category for place in places | unique:'category'">
    <option value="0">Default</option>
    // unique options from the categories
</select>

또는 Lodash를 사용하여 직접 필터를 작성할 수도 있습니다.

app.filter('unique', function() {
    return function (arr, field) {
        return _.uniq(arr, function(a) { return a[field]; });
    };
});

'unique'(별명: uniq) 필터를 앵귤러로 사용할 수 있습니다.필터 모듈

사용방법:colection | uniq: 'property'
중첩된 속성으로 필터링할 수도 있습니다.colection | uniq: 'property.nested_property'

네가 할 수 있는 건 그런 거야

function MainController ($scope) {
 $scope.orders = [
  { id:1, customer: { name: 'foo', id: 10 } },
  { id:2, customer: { name: 'bar', id: 20 } },
  { id:3, customer: { name: 'foo', id: 10 } },
  { id:4, customer: { name: 'bar', id: 20 } },
  { id:5, customer: { name: 'baz', id: 30 } },
 ];
}

HTML: 고객 ID를 기준으로 필터링합니다.즉, 중복된 고객을 삭제합니다.

<th>Customer list: </th>
<tr ng-repeat="order in orders | unique: 'customer.id'" >
   <td> {{ order.customer.name }} , {{ order.customer.id }} </td>
</tr>

결과
고객 리스트:
foo 10
바 20
바즈 30

이 코드는 나에게 효과가 있어.

app.filter('unique', function() {

  return function (arr, field) {
    var o = {}, i, l = arr.length, r = [];
    for(i=0; i<l;i+=1) {
      o[arr[i][field]] = arr[i];
    }
    for(i in o) {
      r.push(o[i]);
    }
    return r;
  };
})

그리고 나서.

var colors=$filter('unique')(items,"color");

카테고리를 리스트 하고 싶은 경우는, 뷰에 자신의 의도를 명확하게 기술하는 것이 좋다고 생각합니다.

<select ng-model="orderProp" >
  <option ng-repeat="category in categories"
          value="{{category}}">
    {{category}}
  </option>
</select>

컨트롤러:

$scope.categories = $scope.places.reduce(function(sum, place) {
  if (sum.indexOf( place.category ) < 0) sum.push( place.category );
  return sum;
}, []);

여기 간단하고 일반적인 예가 있습니다.

필터:

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;
  };
})

마크업:

<div ng-repeat = "item in items | unique:'name'">
  {{ item.name }}
</div>
<script src="your/filters.js"></script>

@thethakuri의 답변을 연장하여 유니크한 멤버에게 깊이를 부여하기로 했습니다.여기 암호가 있습니다.Angular 전체를 포함하지 않으려는 분들을 위한 것입니다.이 기능만을 위한 UI 모듈.이미 Angular를 사용하고 있는 경우UI, 다음 답변을 무시합니다.

app.filter('unique', function() {
    return function(collection, primaryKey) { //no need for secondary key
      var output = [], 
          keys = [];
          var splitKeys = primaryKey.split('.'); //split by period


      angular.forEach(collection, function(item) {
            var key = {};
            angular.copy(item, key);
            for(var i=0; i<splitKeys.length; i++){
                key = key[splitKeys[i]];    //the beauty of loosely typed js :)
            }

            if(keys.indexOf(key) === -1) {
              keys.push(key);
              output.push(item);
            }
      });

      return output;
    };
});

<div ng-repeat="item in items | unique : 'subitem.subitem.subitem.value'"></div>

오브젝트가 아닌 문자열 배열이 있어서 이 방법을 사용했습니다.

ng-repeat="name in names | unique"

다음 필터를 사용합니다.

angular.module('app').filter('unique', unique);
function unique(){
return function(arry){
        Array.prototype.getUnique = function(){
        var u = {}, a = [];
        for(var i = 0, l = this.length; i < l; ++i){
           if(u.hasOwnProperty(this[i])) {
              continue;
           }
           a.push(this[i]);
           u[this[i]] = 1;
        }
        return a;
    };
    if(arry === undefined || arry.length === 0){
          return '';
    }
    else {
         return arry.getUnique(); 
    }

  };
}

갱신하다

세트 사용을 권장하고 있었습니다만, ng-repeat도 맵도 ng-repeat도 어레이에서만 동작하기 때문에 사용할 수 없습니다.그러니 이 대답은 무시하세요.어쨌든 중복을 걸러낼 필요가 있는 경우, 다른 방법에서 말한 바와 같이angular filters시작」섹션의 링크를 다음에 나타냅니다.


구답

세트에 추가할 때 어레이 데이터 구조 대신 ECMAScript 2015(ES6) 표준 Set Data 구조를 사용할 수 있습니다(세트는 반복 값을 허용하지 않음).매우 사용하기 쉽다:

var mySet = new Set();

mySet.add(1);
mySet.add(5);
mySet.add("some text");
var o = {a: 1, b: 2};
mySet.add(o);

mySet.has(1); // true
mySet.has(3); // false, 3 has not been added to the set
mySet.has(5);              // true
mySet.has(Math.sqrt(25));  // true
mySet.has("Some Text".toLowerCase()); // true
mySet.has(o); // true

mySet.size; // 4

mySet.delete(5); // removes 5 from the set
mySet.has(5);    // false, 5 has been removed

mySet.size; // 3, we just removed one value

다들 자기들만의 버전을 던지고 있는 것 같아unique★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★비평은 대환영입니다.

angular.module('myFilters', [])
  .filter('unique', function () {
    return function (items, attr) {
      var seen = {};
      return items.filter(function (item) {
        return (angular.isUndefined(attr) || !item.hasOwnProperty(attr))
          ? true
          : seen[item[attr]] = !seen[item[attr]];
      });
    };
  });

여기 템플릿만의 방법이 있습니다(단, 순서를 유지하는 것은 아닙니다).또한 결과도 순서가 매겨집니다.이것은 대부분의 경우에 도움이 됩니다.

<select ng-model="orderProp" >
   <option ng-repeat="place in places | orderBy:'category' as sortedPlaces" data-ng-if="sortedPlaces[$index-1].category != place.category" value="{{place.category}}">
      {{place.category}}
   </option>
</select>

위의 필터 중 어느 것도 문제를 수정하지 않았기 때문에 공식 github 문서에서 필터를 복사해야 했습니다.그런 다음 위의 답변에서 설명한 대로 사용하십시오.

angular.module('yourAppNameHere').filter('unique', function () {

반환 함수(항목, filterOn) {

if (filterOn === false) {
  return items;
}

if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
  var hashCheck = {}, newItems = [];

  var extractValueToCompare = function (item) {
    if (angular.isObject(item) && angular.isString(filterOn)) {
      return item[filterOn];
    } else {
      return item;
    }
  };

  angular.forEach(items, function (item) {
    var valueToCheck, isDuplicate = false;

    for (var i = 0; i < newItems.length; i++) {
      if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
        isDuplicate = true;
        break;
      }
    }
    if (!isDuplicate) {
      newItems.push(item);
    }

  });
  items = newItems;
}
return items;
  };

});

네스트된 키를 기반으로 고유한 데이터를 가져오는 경우:

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;
        };
    });

이렇게 불러주세요.

<div ng-repeat="notify in notifications | unique: 'firstlevel':'secondlevel'">

다음 필터 추가:

app.filter('unique', function () {
return function ( collection, keyname) {
var output = [],
    keys = []
    found = [];

if (!keyname) {

    angular.forEach(collection, function (row) {
        var is_found = false;
        angular.forEach(found, function (foundRow) {

            if (foundRow == row) {
                is_found = true;                            
            }
        });

        if (is_found) { return; }
        found.push(row);
        output.push(row);

    });
}
else {

    angular.forEach(collection, function (row) {
        var item = row[keyname];
        if (item === null || item === undefined) return;
        if (keys.indexOf(item) === -1) {
            keys.push(item);
            output.push(row);
        }
    });
}

return output;
};
});

마크업 갱신:

<select ng-model="orderProp" >
   <option ng-repeat="place in places | unique" value="{{place.category}}">{{place.category}}</option>
</select>

이건 과잉 살상일 수도 있지만 나한테는 효과가 있어

Array.prototype.contains = function (item, prop) {
var arr = this.valueOf();
if (prop == undefined || prop == null) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == item) {
            return true;
        }
    }
}
else {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i][prop] == item) return true;
    }
}
return false;
}

Array.prototype.distinct = function (prop) {
   var arr = this.valueOf();
   var ret = [];
   for (var i = 0; i < arr.length; i++) {
       if (!ret.contains(arr[i][prop], prop)) {
           ret.push(arr[i]);
       }
   }
   arr = [];
   arr = ret;
   return arr;
}

개별 함수는 위에서 정의한 포함 함수에 따라 달라집니다. 할 수 있습니다.array.distinct(prop);소품

그냥 말하면 요.$scope.places.distinct("category");

독자적인 어레이를 작성합니다.

<select name="cmpPro" ng-model="test3.Product" ng-options="q for q in productArray track by q">
    <option value="" >Plans</option>
</select>

 productArray =[];
angular.forEach($scope.leadDetail, function(value,key){
    var index = $scope.productArray.indexOf(value.Product);
    if(index === -1)
    {
        $scope.productArray.push(value.Product);
    }
});

언급URL : https://stackoverflow.com/questions/15914658/how-to-make-ng-repeat-filter-out-duplicate-results

반응형