数组 – 在推送之前检查重复的项目

前端之家收集整理的这篇文章主要介绍了数组 – 在推送之前检查重复的项目前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
早上好,

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

我已经尝试过这个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;
     }


 }

** FIX **

$scope.Products = $scope.$storage.Products == undefined ? [] : $scope.$storage.Products;
$scope.logItem = function($index,amount) {
    $scope.newItem = {
        Brand: brandName,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");
    };

}

解决方法

像这样的东西

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

Look fiddle

猜你在找的Angularjs相关文章