Convert Form Fields Into Json Object
I have the following form:
Solution 2:
My variant:
arr = $("#myForm").serializeArray();
var res={};
var m,o;
arr.forEach(function(item){
m = item.name.match(/[^\]\[]+/g);
o = res;
m.forEach(function(v,i,a){
if(o[v] === undefined) {
if(i+1 !== a.length) {
o[v] = {};
o = o[v];
return;
}
o[v] = [item.value];
} else {
if(i+1 !== a.length) {
o = o[v];
return;
}
o[v].push(item.value);
}
});
})
console.log(res)
$('<pre>'+JSON.stringify(res)+'</pre>').appendTo('#result')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="myForm" method="POST">
<input type="text" name="matrix[]" value="1"/><br/>
<input type="text" name="matrix[]" value="2"/><br/>
<input type="text" name="matrix[]" value="3"/><br/>
<input type="text" name="multi_matrix[colors][]" value="red"/><br/>
<input type="text" name="multi_matrix[colors][]" value="blue"/><br/>
<input type="text" name="multi_matrix[weight][]" value="75"/><br/>
<input type="text" name="multi_matrix[weight][]" value="83"/><br/>
<input type="text" name="multi_matrix[weight_real][]" value="83.32"/><br/>
<input type="text" name="multi_matrix[weight_real][]" value="83.65"/><br/>
<input type="text" name="multi_matrix[price][unreal][]" value="383.32"/><br/>
<input type="text" name="multi_matrix[price][unreal][]" value="183.65"/><br/>
<input type="submit" value="Send">
</form>
<div id="result"></div>
{
"matrix": ["1", "2", "3"],
"multi_matrix": {
"colors": ["red", "blue"],
"weight": ["75", "83"],
"weight_real": ["83.32", "83.65"],
"price": {
"unreal": ["383.32", "183.65"]
}
}
}
Post a Comment for "Convert Form Fields Into Json Object"