【问题标题】:Check for duplicate items before pushing推送前检查重复项
【发布时间】:2014-12-01 09:19:30
【问题描述】:

早上好,

我想将新项目推送到数组中(我们可以这样做),但在推送之前检查重复项以防止在数组中重复项目。

我已经尝试过这个 example,但我没有成功地让它与我们的代码一起工作。

如果有人知道更好的解决方案或知道我们哪里出了问题,请尽快告诉我们。 谢谢。

** JS **

 $scope.Products = $scope.$storage.Products == undefined ? [] : $scope.$storage.Products;
 $scope.logItem = function($index, brandName, partNumber, productName, amount) {

     $scope.newItem = {
         Brand: brandName,
         Part: partNumber,
         Product: productName,
         Amount: amount
     };

     var duplicateItem = $scope.Products.reduce(function(previous, i) {
         if ($scope.newItem === i) return true;
         return previous
     }, false);

     if (duplicateItem) {
         alert("Already Logged");
     } else {
         alert("Item Logged");
         $scope.Products.push($scope.newItem);
         $scope.$storage.Products = $scope.Products;
     }


 }

** 修复 **

$scope.Products = $scope.$storage.Products == undefined ? [] : $scope.$storage.Products;
$scope.logItem = function($index, brandName, partNumber, productName, amount) {
    $scope.newItem = {
        Brand: brandName,
        Part: partNumber,
        Product: productName,
        Amount: amount
    };
    var isDuplicate = false;
    $scope.Products.forEach(function(element) {
        if (JSON.stringify(element) === JSON.stringify($scope.newItem)) {
            isDuplicate = true;
            return false;
        }
    });
    if (!isDuplicate) {
        alert("Item Logged");
        $scope.Products.push($scope.newItem);
        $scope.$storage.Products = $scope.Products;
    } else {
        alert("Already Logged");
    };

}

【问题讨论】:

    标签: arrays json angularjs duplicate-removal


    【解决方案1】:

    类似的东西

    $scope.Products.forEach(function (element) {
        if (JSON.stringify(element) === JSON.stringify($scope.newItem)) {
            isDuplicate = true;
            return false;
        }
    });
    

    Look fiddle

    【讨论】:

      【解决方案2】:

      在推送到数组之前,您始终可以检查推送到数组是否安全。

      if ($scope.ITEMS.indexOf(ITEM) == -1) {
        // SAFE
        $scope.ITEMS.push(ITEM);
      }
      

      【讨论】:

        【解决方案3】:

        http://jsfiddle.net/u8Fuk/24/.

        您可以使用unique 过滤器。为此,您需要为 angularui 添加依赖项, 那么你可以简单地做

        ng-repeat="item in items | unique:'item' "
        

        【讨论】:

          【解决方案4】:

          另外,您可以在 underscore.js 中使用 _.reject 或 _.filter 函数来防止基于条件的重复值

          【讨论】:

            猜你喜欢
            • 2011-12-04
            • 1970-01-01
            • 2012-11-23
            • 1970-01-01
            • 2011-02-03
            • 2015-02-21
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多