重建javascript数组

时间:2016-04-18 13:28:55

标签: javascript arrays multidimensional-array

我有这个数组

"Emergency services":[  
  {  
     "benefit":"Emergency room care",
     "category":"Emergency services",
     "limit":"232323",
     "limit_individual":"232323",
     "max_day_limit":"2332",
     "plan":"newPlan",
     "isChecked":false
  },
  {  
     "benefit":"Ambulance service",
     "category":"Emergency services",
     "limit":"3223",
     "limit_individual":"2323",
     "max_day_limit":"2323",
     "plan":"newPlan",
     "isChecked":true
  },
  {  
     "benefit":"Urgent care centers/facilities",
     "category":"Emergency services",
     "limit":"2323",
     "limit_individual":"2323",
     "max_day_limit":"2323",
     "plan":"newPlan",
     "isChecked":true
  }
],

我需要重建到

{  
     "benefit":"Urgent care centers/facilities",
     "category":"Emergency services",
     "limit":"2323",
     "limit_individual":"2323",
     "max_day_limit":"2323",
     "plan":"newPlan"
  }

如果isChecked值为true。

如果isChecked值为false,我想从数组中丢弃整个数组对象,然后将生成的数组发送到后端API

1 个答案:

答案 0 :(得分:1)

您可以使用JS中的简单for-loop来实现此目的:

var input = [  
  {  
     "benefit":"Emergency room care",
     "category":"Emergency services",
     "limit":"232323",
     "limit_individual":"232323",
     "max_day_limit":"2332",
     "plan":"newPlan",
     "isChecked":false
  },
  {  
     "benefit":"Ambulance service",
     "category":"Emergency services",
     "limit":"3223",
     "limit_individual":"2323",
     "max_day_limit":"2323",
     "plan":"newPlan",
     "isChecked":true
  },
  {  
     "benefit":"Urgent care centers/facilities",
     "category":"Emergency services",
     "limit":"2323",
     "limit_individual":"2323",
     "max_day_limit":"2323",
     "plan":"newPlan",
     "isChecked":true
  }];

  var output = [];

  for (var i=0; i<input.length; i+=1) {
    var item = input[i];

    if (item.isChecked) {
        //delete the isChecked property
        delete item.isChecked;
        //add item to output
        output.push(item);
    }
  }

  console.log(output);

检查出来: https://jsfiddle.net/ynpu6tv1/