如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
当前回答
这是对Tobias Cohen函数的改进,该函数在多维数组中运行良好:
http://jsfiddle.net/BNnwF/2/
然而,这不是一个jQuery插件,但如果您想这样使用它,只需几秒钟就可以将它变成一个:只需替换函数声明包装器:
function serializeFormObject(form)
{
...
}
具有:
$.fn.serializeFormObject = function()
{
var form = this;
...
};
我想这与梅斯克的解决方案相似,因为它做了相同的事情,但我认为这有点干净和简单。我还将macek的测试用例输入添加到小提琴中,并添加了一些额外的输入。到目前为止,这对我来说很好。
function serializeFormObject(form)
{
function trim(str)
{
return str.replace(/^\s+|\s+$/g,"");
}
var o = {};
var a = $(form).serializeArray();
$.each(a, function() {
var nameParts = this.name.split('[');
if (nameParts.length == 1) {
// New value is not an array - so we simply add the new
// value to the result object
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
}
else {
// New value is an array - we need to merge it into the
// existing result object
$.each(nameParts, function (index) {
nameParts[index] = this.replace(/\]$/, '');
});
// This $.each merges the new value in, part by part
var arrItem = this;
var temp = o;
$.each(nameParts, function (index) {
var next;
var nextNamePart;
if (index >= nameParts.length - 1)
next = arrItem.value || '';
else {
nextNamePart = nameParts[index + 1];
if (trim(this) != '' && temp[this] !== undefined)
next = temp[this];
else {
if (trim(nextNamePart) == '')
next = [];
else
next = {};
}
}
if (trim(this) == '') {
temp.push(next);
} else
temp[this] = next;
temp = next;
});
}
});
return o;
}
其他回答
function serializedArray2Object(array){
let obj = {};
array.forEach(function(item){
if(obj[item['name']] === undefined){
obj[item['name']] = item['value'];
}else if(Array.isArray(obj[item['name']])){
obj[item['name']] = [...obj[item['name']],item['value']]
}else{
obj[item['name']] = [obj[item['name']],item['value']];
}
});
return obj;
}
使用
serializedArray2Object($('#form').serializeArray())
我刚刚从jQuery中发现了这个函数,并编写了一个到对象的转换器,这样数组就变成了一个对象。
使用此项:
var sf = $('#mainForm').serialize(); // URL encoded string
sf = sf.replace(/"/g, '\"'); // Be sure all "s are escaped
sf = '{"' + sf.replace(/&/g, '","'); // Start "object", replace tupel delimiter &
sf = sf.replace(/=/g, '":"') + '"}'; // Replace equal sign, add closing "object"
// Test the "object"
var formdata = eval("(" + sf + ")");
console.log(formdata);
即使在非常复杂的形式上,它也像一种魅力。
一行(除了jQuery之外没有依赖项)使用传递给map方法的函数的固定对象绑定。
$('form').serializeArray().map(function(x){this[x.name] = x.value; return this;}.bind({}))[0]
它做什么?
"id=2&value=1&comment=ok" => Object { id: "2", value: "1", comment: "ok" }
适用于渐进式web应用程序(可以轻松支持常规表单提交操作和ajax请求)
我发现Tobias Cohen的代码有一个问题(我没有足够的分数来直接评论它),否则它对我来说是有效的。如果您有两个同名的选择选项,都是value=“”,原始代码将生成“name”:“”而不是“name”:[”,“”]
我认为这可以通过在第一个if条件中添加“||o[this.name]==''”来解决:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] || o[this.name] == '') {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
另一个答案
document.addEventListener(“DOMContentLoaded”,函数(){setInterval(函数){var form=document.getElementById('form')||document.querySelector('form[name=“userprofile”]');var json=Array.from(new FormData(form)).map(函数(e,i){this[e[0]〕=e[1];return this;}.bind({}))[0];console.log(json)document.querySelector('#asJSON').value=JSON.stringify(JSON);}, 1000);})<form name=“userprofile”id=“form”><p>名称<input-type=“text”Name=“firstname”value=“John”/></p><p>姓氏<input name=“lastname”value=“Smith”/></p><p>工作<input name=“employment[name]”value=“inc,inc.”/></p><p>工作时间:<input name=“employment[since]”value=“2017”/></p><p>照片<input-type=“file”/></p><p>发送<input-type=“submit”/></p></form>JSON:<textarea id=“asJSON”></textarea>
表单数据:https://developer.mozilla.org/en-US/docs/Web/API/FormData