A similar question is addressed here: Convert form data to JavaScript object with jQuery with the following solution:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
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 || '';
}
});
return o;
};
However that doesn't work when you want to have JSON with nested objects. For instance, for this form:
Employee name: <input type="text" id="employee" name="name"/>
Department name: <input type="text" id="department" name="department.name"/>
Department chief1: <input type="text" id="chief1" name="department.chief[0]"/>
Department chief2: <input type="text" id="chief2" name="department.chief[1]"/>
I am getting: {"name":"John","department.name":"IT" , "department.chief[0]":"Mike" "department.chief[1]":"Lucas"}
but what I do need is {"name":"John","department" : {"name":"IT"}, "chief" : [ "Mike", "Lucas" }
Is there any adaptation of serializeObject that does it this way?
To provide some background: I need this because I am submitting an AJAX call to a Spring MVC controller and Jackson expects that format to create the nested objects.