I need to make a JSON out of a form with multiple fields with same name param but I want to group it as array? is it possible?
EDITED: I tried the suggested solution, but I can't use the value for name as key in the new array... Can you help me out how could I change it as {name:value[]} instead of {name:name, value:value[]} ?
var json = JSON.stringify($("#frm").serializeArray());
$("#json").html(json);
var myArray = $("#frm").serializeArray();
var groups = {};
for (var i = 0; i < myArray.length; i++) {
var groupName = myArray[i].name;
if (!groups[groupName]) {
groups[groupName] = [];
}
groups[groupName].push(myArray[i].value);
}
myArray = [];
for (var groupName in groups) {
myArray.push({name: groupName, value: groups[groupName]});
}
var json = JSON.stringify(myArray);
$("#json").html(json);
var myArray2 = [];
for (var groupName in groups) {
myArray2.push({groupName: groups[groupName]});
}
var json2 = JSON.stringify(myArray2);
$("#json2").html(json2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<form id="frm">
<input type="text" name="a" value="1"/>
<input type="text" name="b" value="2"/>
<input type="text" name="a" value="3"/>
<input type="text" name="b" value="4"/>
</form>
<br/>
Edited: I followed the suggested solution, its like this now:
<p id="json">
</p>
<br/>
but I can't use the value of "name" as key for the array
<p id="json2">
</p>
<br/>
<br/>
is it possible to make it like this instead?
<br/>
<p>
{"a":[1,3], "b":[2,4]}
</p>