Skip to content

Instantly share code, notes, and snippets.

@oivoodoo
Created September 2, 2011 12:40
Show Gist options
  • Save oivoodoo/1188511 to your computer and use it in GitHub Desktop.
Save oivoodoo/1188511 to your computer and use it in GitHub Desktop.
/*
* Small serialize form snippet supporting one level nested attributes.
*/
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
var pattern = /\[[\w\d\(\)_]+\]/;
$.each(a, function() {
var key = this.name;
var name = key.replace(/^\w+\[/, '').replace(/\]/, '');
key = key.replace(pattern, '');
o[key] = o[key] || [];
if (this.name != key) {
if (o[key].length == 0) {
var hash = {};
hash[name] = this.value;
o[key].push(hash);
} else {
for(var i = 0; i < o[key].length; i++) {
if (!o[key][i][name]) {
o[key][i][name] = this.value;
break;
}
}
}
} else {
o[key] = this.value
}
});
return o;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment