如何从angularjs中给定的json数据获得质量率

时间:2017-07-03 11:57:10

标签: javascript angularjs json

Json数据:

{
  "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.discountedRate得到$scope.quantity

那么,如何通过比较食物的数量从json数据中获得折扣率。

1 个答案:

答案 0 :(得分: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