Skip to content

Instantly share code, notes, and snippets.

@yanneves
Created September 15, 2014 13:07
Show Gist options
  • Save yanneves/cf0119fea456c7b9f0dd to your computer and use it in GitHub Desktop.
Save yanneves/cf0119fea456c7b9f0dd to your computer and use it in GitHub Desktop.
_.serialize Underscore.js mixin
_.mixin({
// Serialize key-value pairs of an object into urlencoded format
serialize: function(obj) {
var pairs = _.pairs(obj);
return _.reduce(pairs, function(memo, pair) {
var key = _.first(pair), value = _.last(pair);
value = _.isFunction(value) ? value() : value;
return memo + '&' + encodeURIComponent(key) + '=' + encodeURIComponent(value);
}, '').replace('&', '').replace(/%20/g, '+');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment