SerializeArray结果为单个数组

时间:2018-04-09 07:47:30

标签: javascript jquery

我使用JS serializeArray函数跟踪serializeArray。

0: {name: "sub_maintenance_template[1][maintenance_problem_id]", value: "471354"}
1:
{name: "sub_maintenance_template[1][maintenance_location_id]", value: "38565"}
2:
{name: "sub_maintenance_template[1][maintenance_priority_id]", value: "24879"}
3:
{name: "sub_maintenance_template[1][days_to_complete]", value: "2"}
4:
{name: "sub_maintenance_template[1][description]", value: "fff"}
5:
{name: "sub_maintenance_template[1][order_num]", value: "1"}

我想把它变成单个数组,如下所示:

[sub_maintenance_template] => array( 
  [0] => array( 
          [maintenance_problem_id] => 471354
          [maintenance_location_id] => 38565
          [maintenance_priority_id] => 24879
          [days_to_complete] => 2
          [description] => fff
          [order_num] => 1
   ) 
)

有没有办法实现这个目标?

我尝试使用$ .each但它失败了。

1 个答案:

答案 0 :(得分:0)

试试这个,

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
var outputAry = temp = [];
var inputAry = [{name: "sub_maintenance_template[1][maintenance_problem_id]", value: "471354"},
{name: "sub_maintenance_template[1][maintenance_location_id]", value: "38565"},
{name: "sub_maintenance_template[1][maintenance_priority_id]", value: "24879"},
{name: "sub_maintenance_template[1][days_to_complete]", value: "2"},
{name: "sub_maintenance_template[1][description]", value: "fff"},
{name: "sub_maintenance_template[1][order_num]", value: "1"}];

$(inputAry).each(function( index) {
  var text = inputAry[index].name.replace("sub_maintenance_template[1][", "").replace("]", "");
  temp[text] =  inputAry[index].value;
});
outputAry['sub_maintenance_template'] = Array(temp);
console.log(outputAry);
</script>