2017-08-11 27 views
1

我正試圖實現離線添加到購物車功能。如何在推送前檢查JSON中的天氣項目

在這裏,我有添加到購物車功能。

$scope.payloadData = []; 

    $scope.add_to_cart = function(MRP, ProductId, ProductVariantId) { 

    $scope.dt = { //It is JSON string 
     "Unitprice": MRP, 
     "ProductId": ProductId, 
     "Productvariantid": ProductVariantId 
} 

//If user is not logged in     
if(localStorage.getItem('tokenvalue') != undefined) { 
    $scope.payloadData.push($scope.dt);      
    for(var i=0;i<$scope.payloadData.length;i++) { 
    $scope.cmp = angular.equals($scope.payloadData, $scope.payloadData); 
    if($scope.cmp == "false") { // Not working 
    $scope.payloadData.push($scope.dt); //Push if item not exist in $scope.payloadData 
    } 
    else{ //do nothing }      
}  
} 

$scope.payloaddata after pushed is ://It is JSON array 
[ 
    { 
     "Unitprice": 500, 
     "ProductId": 3,   
     "Productvariantid": 3 
    } 
] 

如何查詢天氣$ scope.dt & $ scope.payloadData數據推前相同。

+0

您可以對此使用'indexOf'函數。 'if($ scope.payloaddata.indexOf($ scope.dt)== -1){...}' –

+0

你想檢查$ scope.day已經存在於$ scope.payloaddata數組中嗎? – Gaara

+0

現在。我想在被推之前檢查。 –

回答

0

使用hasOwnProperty方法來確定

**myObj.hasOwnProperty(newproperty to push)** 
0

既然你是在你的對象只使用基本數據類型。這是檢查$ scope.dt是否已存在於$ scope.payloaddata中的一種方法

function containsObject(objStr, list) { 
    var i; 
    for (i = 0; i < list.length; i++) { 
     if (JSON.stringify(list[i]) === objStr) { 
      return true; 
     } 
    } 
    return false; 
} 

var dtStr = JSON.stringify($scope.dt); 
containsObject(dtStr, $scope.payloaddata); 
相關問題