Created
April 8, 2013 22:45
-
-
Save cvan/5341215 to your computer and use it in GitHub Desktop.
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
$.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 (data[group].length <= idx && field) { | |
data[group][idx] = {}; | |
} | |
if (field && v) { | |
data[group][idx][field] = v; | |
} | |
if (typeof _ === 'function') { | |
// Strip null values and empty objects. | |
data[group] = _.reject(_.compact(data[group]), function(x) { return _.isObject(x) && _.isEmpty(x) }); | |
} | |
delete data[k]; | |
} else { | |
data[k] = v; | |
} | |
}); | |
return data; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment