我使用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>
关于javascript - 如何将serializeArray更改为普通对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47591441/