Skip to content

Instantly share code, notes, and snippets.

@mattbasta
Forked from cvan/serializeObject.js
Last active December 15, 2015 23:38
Show Gist options
  • Save mattbasta/5341254 to your computer and use it in GitHub Desktop.
Save mattbasta/5341254 to your computer and use it in GitHub Desktop.
$.fn.serializeObject = function() {
var data = {};
_.each($(this).serializeArray(), function(v, k) {
k = v.name;
v = v.value;
if (_.contains(k, '__prefix__')) {
return;
}
if (k.match(/\-\d+\-/g)) {
// Turn `users-0-name=Basta` into
//
// {
// "users": [
// {
// "name: "Basta"
// }
// ],
// ...
// }
//
var chunks = k.split('-');
var group = chunks[0];
var idx = parseInt(chunks[1], 10);
var field = chunks[2];
if (!(group in data)) {
data[group] = [];
}
if (!field || !v) {
return;
}
if (data[group].length <= idx && field) {
data[group][idx] = {};
}
data[group][idx][field] = v;
delete data[k]; // XXX: does this do anything?
} else {
data[k] = v;
}
});
return data;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment