Skip to content

Instantly share code, notes, and snippets.

@paulwib
Created May 17, 2013 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulwib/5598355 to your computer and use it in GitHub Desktop.
Save paulwib/5598355 to your computer and use it in GitHub Desktop.
Serialize a form to a JavaScript object with jQuery
function serializeObject($form) {
var counters = {},
serialized = {};
$form.serializeArray().forEach(function(input) {
// Split name into tokens, fixing numeric indexes where neccessary
var tokens = input.name.split('[').map(function(value) {
value = value.replace(']', '');
if(value === '') {
if(typeof counters[input.name] == "undefined") {
counters[input.name] = 0;
}
value = counters[input.name]++;
}
else if(value.match(/^[0-9]+$/)) {
value = parseInt(value, 10);
}
return value;
});
// Add to serialized object
var ob = serialized;
tokens.forEach(function(value, index, arr) {
if(index === tokens.length-1) {
ob[value] = input.value;
return;
}
if(typeof ob[value] === "undefined") {
ob[value] = typeof tokens[index + 1] == "number" ? [] : {};
}
ob = ob[value];
});
});
return serialized;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment