Skip to content

Instantly share code, notes, and snippets.

@vernondegoede
Created May 20, 2015 09:22
Show Gist options
  • Save vernondegoede/8dab074d09ef4dc68e41 to your computer and use it in GitHub Desktop.
Save vernondegoede/8dab074d09ef4dc68e41 to your computer and use it in GitHub Desktop.
Serialize multidimensional form into a JavaScript object
$.fn.serializeObject = function () {
var o = {};
var serialized = {};
$("[name]", this).each(function () {
var name = $(this).attr('name');
var value = $(this).val();
var nameBits = name.split('[');
var previousRef = serialized;
for (var i = 0, l = nameBits.length; i < l; i++) {
var nameBit = nameBits[i].replace(']', '');
if (!previousRef[nameBit]) {
previousRef[nameBit] = {};
}
if (i != nameBits.length - 1) {
previousRef = previousRef[nameBit];
} else if (i == nameBits.length - 1) {
previousRef[nameBit] = value;
}
}
});
return serialized;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment