Created
September 15, 2014 13:07
-
-
Save yanneves/cf0119fea456c7b9f0dd to your computer and use it in GitHub Desktop.
_.serialize Underscore.js mixin
This file contains 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
_.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