如何将serializearray更改为普通对象



i使用 serializeArray获取所有元素,而我得到的对象如

[{name: "code[1][barcode]", value: "45534"},
{name: "code[1][rf_id]", value: "535353"},
{name: "code[1][serialize]", value: ""},
{name: "code[2][barcode]", value: "45534"},
{name: "code[2][rf_id]", value: "535353"},
{name: "code[2][serialize]", value: ""},
{name: "custodian[]", value: "3"},
{name: "custodian[]", value: "4"},
{name: "custodian[]", value: "5"}]

我想像这个

一样转换
{
    code:[
            {barcode:"45534",rf_id:"535353",serialize:""},
            {barcode:"45534",rf_id:"535353",serialize:""}
        ],
    custodian: [3,4,5]
}

目前我正在使用此脚本

var x = $('form#acquiredetail').serializeArray();
console.log(x);
var formData = {};
$.each(x, function(i, field){
    if(field.value.trim() != ""){
      formData[field.name] = field.value;
    }
});

并获得输出为

尽管我能够正确地获得code的价值,但是在后端/Laravel中,但问题是custodian,但我获得了最后一个值,

custodian[]:"5"

我该如何解决。还是有任何更好的解决方案?

我的目标是将所有元素值传递给使用简短和常见代码的PHP。请建议是否有此选择

运行代码段并享受:)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var x = 
[{name: "code[1][barcode]", value: "45534"},
{name: "code[1][rf_id]", value: "535353"},
{name: "code[1][serialize]", value: ""},
{name: "code[2][barcode]", value: "45534"},
{name: "code[2][rf_id]", value: "535353"},
{name: "code[2][serialize]", value: ""},
{name: "custodian[]", value: "3"},
{name: "custodian[]", value: "4"},
{name: "custodian[]", value: "5"}];
   var formData = {};
    $.each(x, function(i, field){
    	if(field.value.trim() != ""){
    		if(formData[field.name] != undefined){
    			var val = formData[field.name];
    			if(!Array.isArray(val)){
    				 arr = [val];
    			}
    			arr.push(field.value.trim());
    			formData[field.name] = arr;
    		}else{
    		  formData[field.name] = field.value;
    		}
        }
    });
    console.log(formData );
    </script>

您将必须更改序列化,以查看元素是否以数组表示[]结束并根据元素计数重建键:

var x = [{name: "code[1][barcode]", value: "45534"},
{name: "code[1][rf_id]", value: "535353"},
{name: "code[1][serialize]", value: ""},
{name: "code[2][barcode]", value: "45534"},
{name: "code[2][rf_id]", value: "535353"},
{name: "code[2][serialize]", value: ""},
{name: "custodian[]", value: "3"},
{name: "custodian[]", value: "4"},
{name: "custodian[]", value: "5"}];
var formData = {};
var formDataArrays = {};
$.each(x, function(i, field){
    if(field.value.trim() != ""){
      if (/[]$/.test(field.name)) {
        var fName = field.name.substr(0,field.name.length-2);
        if (!formDataArrays[fName]) {
          formDataArrays[fName] = [];
        }
        formData[fName+"["+formDataArrays[fName].length+"]"] = field.value;
        formDataArrays[fName].push(field.value);
      } else {
        formData[field.name] = field.value;
      }
    }
});
console.info(formData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

相关内容

  • 没有找到相关文章

最新更新