Skip to content

Instantly share code, notes, and snippets.

@j-mcnally
Created October 5, 2011 04:26
Show Gist options
  • Save j-mcnally/1263632 to your computer and use it in GitHub Desktop.
Save j-mcnally/1263632 to your computer and use it in GitHub Desktop.
Expanded Serializer
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
var oldName = this.name;
this.name = this.name.replace(/\[\]/g, '');
if (this.name.indexOf('[') >= 0) {
var innerName = this.name.match(/.*\[(.*)\]/)[1];
var outterName = this.name.split("[")[0];
if (o[outterName]) {
if (o[outterName][innerName]) {
if (!o[outterName][innerName].push) {
o[outterName][innerName] = [o[outterName][innerName]];
}
o[outterName][innerName].push(this.value || '');
}
else {
console.log(this.name);
if ((oldName).indexOf('[]') >= 0) {
o[outterName][innerName] = [this.value] || '';
}
else {
o[outterName][innerName] = this.value || '';
}
}
}
else {
o[outterName] = {};
if (o[outterName][innerName]) {
if (!o[outterName][innerName].push) {
o[outterName][innerName] = [o[outterName][innerName]];
}
o[outterName][innerName].push(this.value || '');
}
else {
console.log(this.name);
if (oldName.indexOf('[]') >= 0) {
o[outterName][innerName] = [this.value] || '';
}
else {
o[outterName][innerName] = this.value || '';
}
}
}
}
else {
if (o[this.name]) {
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;
};
@jeremyckahn
Copy link

I'd say that if it works, then you're good to go. Admittedly it's not the prettiest code I've seen, but that's not really an important detail in the long run. I'd suggest writing a few simple unit tests, since the logic is fairly complex.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment