Skip to content

Instantly share code, notes, and snippets.

@caramelopardalis
Created July 20, 2016 09:53
Show Gist options
  • Select an option

  • Save caramelopardalis/5d9e53d898e6a877c3ede0363c031bf8 to your computer and use it in GitHub Desktop.

Select an option

Save caramelopardalis/5d9e53d898e6a877c3ede0363c031bf8 to your computer and use it in GitHub Desktop.
(function($) {
$.fn.serializeObject = serializeObject;
function serializeObject() {
var result = {};
var array = this.serializeArray();
array.forEach(function(field) {
var remainingName = field.name,
matched,
endIndex,
prevPropName,
currProp = result,
currPropName;
do {
matched = /(\.[^.\[\]]+|\[\d*\])/.exec(remainingName);
if (null === matched) {
endIndex = remainingName.length;
} else if (0 !== matched.index) {
endIndex = matched.index;
} else {
endIndex = matched[1].length;
}
currPropName = remainingName.substring(0, endIndex);
if (null !== currPropName.match(/^\.[^.\[\]]+$/)) {
currPropName = currPropName.substring(1);
if (!currProp.hasOwnProperty(prevPropName)) {
currProp[prevPropName] = {};
}
currProp = currProp[prevPropName];
} else if (null !== currPropName.match(/^\[\d*\]$/)) {
currPropName = currPropName.substring(1, currPropName.length - 1);
if (!currProp.hasOwnProperty(prevPropName)) {
currProp[prevPropName] = [];
}
currProp = currProp[prevPropName];
}
prevPropName = currPropName;
remainingName = remainingName.substring(endIndex);
} while (0 < remainingName.length);
currProp[currPropName] = field.value;
});
return result;
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment