Skip to content

Instantly share code, notes, and snippets.

@suryagaddipati
Created August 8, 2010 18:35
Show Gist options
  • Select an option

  • Save suryagaddipati/514394 to your computer and use it in GitHub Desktop.

Select an option

Save suryagaddipati/514394 to your computer and use it in GitHub Desktop.
jQuery.fn.params2Object = function(){
var d = this.serializeArray()
var data = {};
for (var i = 0; i < d.length; i++) {
var tokens = d[i].name.split('.');
_setValue(data, tokens, d[i].value);
}
return data;
function _setValue(obj, tokens, value, index){
if (tokens.length == 1) {
if (typeof index != 'undefined') {
obj[index] = obj[index] ||
{};
obj[index][tokens[0]] = value;
}
else {
obj[tokens[0]] = value;
}
}
else {
var prop = _getProperty(tokens[0]);
obj[prop.name] = obj[prop.name] || (prop.isArray ? [] : {});
_setValue(obj[prop.name], tokens.slice(1, tokens.length), value, prop.index);
}
}
function _getProperty(token){
var arraySplit = token.split('[');
if (arraySplit.length > 1) {
var propName = arraySplit[0];
var index = arraySplit[1].split(']')[0];
}
else {
var propName = token;
}
return {
name: propName,
index: index,
isArray: token.indexOf(']') > 0
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment