Reputation: 527
<form name = 'test' >
<input type='text' name = 'login'>
<input type='email' name = 'email'>
</form>
If I use JSON.serialize($(form)).serializeArray();
I get [{"name":"login","value":"a value"},{"name":"email","value":"a email"}]
while I need {"login":"a login","email":"a email"}
. How to do that??
Upvotes: 4
Views: 8735
Reputation: 318182
Another way to do this, using plain js and form.elements
as an argument to Array.reduce
var d = [].reduce.call(document.forms['test'].elements,(a,b)=>(a[b.name]=b.value,a),{});
var j = JSON.stringify(d, 0, 4);
console.log(j);
<form name='test'>
<input type='text' name='login'>
<input type='email' name='email'>
</form>
Using 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);
<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>
Upvotes: 1
Reputation: 5773
You could use this:
JSON.stringify($(form).serializeArray().reduce((acc, f) => {
acc[f.name] = f.value
return acc
}, {})
Upvotes: 4
Reputation: 2672
if you get this
[{"name":"login","value":"a value"},{"name":"email","value":"a email"}];
and you need just
{"name":"login","value":"a value"}
just call the variable by their index
var data = [{"name":"login","value":"a value"},{"name":"email","value":"a email"}];
console.log( data[0] )
Upvotes: 0
Reputation: 1311
If you want javascript object:
let dest = {};
$( form )
.serializeArray()
.map( input => dest[ input.name ] = input.value );
And the Json:
console.log( JSON.stringify( dest ) );
Upvotes: 0
Reputation: 1
You can pass the <form>
to FormData()
, iterate key, value pairs of FormData
instance, set each key and value to an object property and value
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>
Upvotes: 4
Reputation: 812
real quick solution that utilizes .serializeArray() would be:
var objArr = JSON.serialize($(form)).serializeArray();
var obj = objArr.pop();
var strJson = JSON.serialize(obj);
Upvotes: -2