<form name = 'test' >
<input type='text' name = 'login'>
<input type='email' name = 'email'>
</form>
如果我使用JSON.serialize($(form)).serializeArray();
我需要 [{"name":"login","value":"a value"},{"name":"email","value":"a email"}]
时获得{"login":"a login","email":"a email"}
。怎么做??
答案 0 :(得分:3)
你可以用这个:
JSON.stringify($(form).serializeArray().reduce((acc, f) => {
acc[f.name] = f.value
return acc
}, {})
答案 1 :(得分:2)
您可以将<form>
传递给FormData()
,迭代FormData
实例的键值对,将每个键和值设置为对象属性和值
let form = document.forms["test"];
let fd = new FormData(form);
let data = {};
for (let [key, prop] of fd) {
data[key] = prop;
}
data = JSON.stringify(data, null, 2);
console.log(data);
<form name='test'>
<input type='text' name='login' value="a login">
<input type='email' name='email' value="a email">
</form>
答案 2 :(得分:0)
如果你想要javascript对象:
let dest = {};
$( form )
.serializeArray()
.map( input => dest[ input.name ] = input.value );
和Json:
console.log( JSON.stringify( dest ) );
答案 3 :(得分:0)
如果你得到这个
[{"name":"login","value":"a value"},{"name":"email","value":"a email"}];
你需要
{"name":"login","value":"a value"}
只需按索引
调用变量即可
var data = [{"name":"login","value":"a value"},{"name":"email","value":"a email"}];
console.log( data[0] )
答案 4 :(得分:0)
另一种方法,使用普通的js和form.elements
作为Array.reduce
的参数
var d = [].reduce.call(document.forms['test'].elements,(a,b)=>(a[b.name]=b.value,a),{});
var j = JSON.stringify(data, 0, 4);
console.log(j);
&#13;
<form name='test'>
<input type='text' name='login'>
<input type='email' name='email'>
</form>
&#13;
使用jQuery
var data = $('form :input').toArray().reduce( (a,b) => (a[b.name]=b.value,a),{})
var json = JSON.stringify(data,0,4);
console.log(data);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='test'>
<input type='text' name='login'>
<input type='email' name='email'>
</form>
&#13;
答案 5 :(得分:-2)
利用.serializeArray()的真正快速解决方案是:
var objArr = JSON.serialize($(form)).serializeArray();
var obj = objArr.pop();
var strJson = JSON.serialize(obj);