0

我从被检查的多选项目中得到一个 json。如何仅根据以下原始 json 中的特定键过滤 json:

原始Json:

 {
        "Reward": [{
            "RewardType": 1,
            "RewardTypeValue": "PartCodes",
            "RewardCode": "CB_USD_20_US",
            "DiscountValue": 20.0
        },
        {
            "RewardType": 1,
            "RewardTypeValue": "PartCodes",
            "RewardCode": "CB_USD_30_US",
            "DiscountValue": 30.0
        },
        {
            "RewardType": 1,
            "RewardTypeValue": "PartCodes",
            "RewardCode": "CB_USD_40_US",
            "DiscountValue": 40.0
        },
        {
            "RewardType": 1,
            "RewardTypeValue": "PartCodes",
            "RewardCode": "CB_USD_50_US",
            "DiscountValue": 50.0
        }]

    }

在下面的代码中,我试图在为“selectedRewards”调用“push”之前只获取 RewardType、RewardCode 和 DiscountType

角代码:

  $scope.rewards = [];
$scope.toggleSelection = function toggleSelection(selectedRewards) {
   var idx = $scope.rewards.indexOf(selectedRewards);
   console.log(selectedRewards);

   // is currently selected
   if (idx > -1) {
     $scope.rewards.splice(idx, 1);
   }

   // is newly selected
   else {

     $scope.rewards.push(selectedRewards);
   }
   console.log($scope.rewards);
};

html代码:

<li ng-repeat="reward in RewardsList ">
           <input id="{{reward.RewardCode}}.{{reward.RewardType}}"
                  type="checkbox"
                  ng-checked="selection.indexOf(reward.RewardCode) > -1"
                  ng-click="toggleSelection(reward)"
                  value="{{reward.RewardCode}}" /> 
    <label  for="{{reward.RewardCode}}">{{reward.RewardCode}}</label>
    </li>

这是我想要得到的预期 json:

{
        "Reward": [{
            "RewardType": 1,
            "RewardCode": "CB_USD_20_US",
            "DiscountValue": 20.0
        },
        {
            "RewardType": 1,
            "RewardCode": "CB_USD_30_US",
            "DiscountValue": 30.0
        },
        {
            "RewardType": 1,
            "RewardCode": "CB_USD_40_US",
            "DiscountValue": 40.0
        },
        {
            "RewardType": 1,
            "RewardCode": "CB_USD_50_US",
            "DiscountValue": 50.0
        }]

    }
4

2 回答 2

2

我真的不知道在您的代码中存储 json 的变量是什么,但是假设您的变量被调用myJson并对应于您共享的原始 json。要获得预期的 json,您可以:

var expectedJson = {
  Reward: myJson.Reward.map(function(item) {
    return {
     RewardType: item.RewardType,
     RewardCode: item.RewardCode,
     DiscountValue: item.DiscountValue
    }
  })
}

Array.prototype.map如果您不熟悉它,请查看:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

于 2017-11-12T21:35:31.550 回答
1

以下解决了我的问题:

代码:

$scope.rewards.push({"RewardType":selectedRewards.RewardType, "RewardCode":selectedRewards.RewardCode," "DiscountValue":selectedRewards.DiscountValue});
于 2017-12-19T18:10:47.783 回答