2017-07-03 35 views
2

JSON數據:如何從給定的JSON數據控管數量速率angularjs

{ 
    "food": { 
    "rates": { 
     "defaultRates": { 
     "cardRate": 600, 
     "discountedRate": 500 
     }, 
     "otherRates": [ 
     { 
      "cardRate": 600, 
      "discountedRate": 400, 
      "fields": [ 
      { 
       "name": "Quantity", 
       "min": 3, 
       "max": 6 
      } 
      ], 
      "name": "3-6 Quantity" 
     }, 
     { 
      "cardRate": 600, 
      "discountedRate": 300, 
      "fields": [ 
      { 
       "name": "Quantity", 
       "min": 7 
      } 
      ], 
      "name": "7+ Quantity" 
     } 
     ] 
    }, 
    "details" : { 
     "name" : "Something" 
    } 
} 

JS代碼:

$scope.food = angular.copy(JSONObject); // Copied JsonObject 

$scope.defaultRates = angular.copy($scope.food.rates.defaultRates); 
$scope.otherRates = angular.copy($scope.food.rates.otherRates); 

$scope.quantity = 4; 

angular.forEach($scope.otherRates, function (otherRate) { 
    angular.forEach(otherRate.fields, function (field) { 
     if($scope.quantity >= field.min){ 
      if(field.max) { 
       if($scope.quantity <= field.max){ 
        $scope.discountedRate = angular.copy(otherRate.discountedRate); 
       } 
      } else { 
       $scope.discountedRate = angular.copy(otherRate.discountedRate); 
      } 
     } else { 
      $scope.discountedRate = angular.copy($scope.defaultRates.discountedRate); 
     } 
    }) 
}); 

如果我安慰$scope.discountedRate我得到7+量率。我想根據我給出的$scope.quantity得到$scope.discountedRate

那麼,如何通過比較食物的數量從json數據中獲得折扣率。

+2

它是外循環中對象'otherRate'的一個屬性....'otherRate.discountedRate' – charlietfl

回答

1

您需要按照以下方式迭代otherRates。

var qty = what ever the user selects 
var matched = {}; 
angular.forEach(food.otherRates, function(otherRate){ 
    angular.forEach(otherRate.fields, function(field){ 
    if(field.min <= qty && field.max >= qty) 
     matched = otherRate; 
    else if(field.min <= qty) 
     matched = otherRate; 
    }); 
}); 
console.log(matched); 
//matched is the other Rate