Created
May 17, 2013 10:43
-
-
Save paulwib/5598355 to your computer and use it in GitHub Desktop.
Serialize a form to a JavaScript object with jQuery
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
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