如何修复angular.forEach中对象的重复?

时间:2015-10-21 20:15:37

标签: javascript angularjs

请帮助我如何解决它。


    schema.controller('schemaDetailCtrl', function($scope, ajaxCall, $location) {
    $scope.storeDetails = [
     {
      "storeName": "Test Store",
      "zipCode": "201301",
      "idenNo": "999999"
     },
     {
      "storeName": "Test2 Store",
      "zipCode": "201014",
      "idenNo": "200037"
     },
     {
      "storeName": "Test3 Store",
      "zipCode": "201014",
      "idenNo": "200137"
     }
   ];

    $scope.zipcodes = new Array();
       angular.forEach($scope.storeDetails, function(store) {
       this.push(store.zipCode);
       console.log(store.zipCode);
    }, $scope.zipcodes);



    Expected Output :
    201301
    201014
    201014

    Actual Output: 
    Error: [ngRepeat:dupes] http://errors.angularjs.org/1.2.20/ngRepeat/dupes?p0=zipcode%20in%20zipcodes&p1=string%3A201014


3 个答案:

答案 0 :(得分:1)

该问题与您的forEach直接无关。它是从视图中抛出的,可以通过将track by添加到ng-repeat语句来解决:

<div ng-repeat="zip in zipcodes track by $index">

如果您不希望数组中出现重复项,那么将其作为一个单独的问题进行过滤。

参考ng-repeat docs

答案 1 :(得分:1)

感谢大家的回答,现在我用了angular.forEach的循环,听起来不错。

for(var i = 0; i < $scope.storeDetails.length; i++) {
    var store = $scope.storeDetails[i];
    if(contains($scope.zipcodes, store.zipCode) === false) {
        $scope.zipcodes.push(store.zipCode);
    }
}

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

答案 2 :(得分:0)

不是将邮政编码复制到另一个数组中以便在视图中显示,而是可以遍历storeDetails数组,然后引用zipCode属性来显示它。

<ul ng-repeat="store in storeDetails">
  <li>{{store.zipCode}}</li>
</ul>

这可以避免数组中重复的问题。