Created
October 5, 2011 04:26
-
-
Save j-mcnally/1263632 to your computer and use it in GitHub Desktop.
Expanded Serializer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.