Skip to content

Instantly share code, notes, and snippets.

@tpai
Last active January 7, 2016 02:09
Show Gist options
  • Save tpai/31ef91ff6643d38abea5 to your computer and use it in GitHub Desktop.
Save tpai/31ef91ff6643d38abea5 to your computer and use it in GitHub Desktop.
$.param() => _.param()
var _ = require("lodash");
var param = function( a ) {
var s = [], add = function( key, value ) {
s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
};
for ( var prefix in a ) {
buildParams( prefix, a[prefix], add );
}
return s.join("&").replace(/%20/g, "+");
};
var buildParams = function( prefix, obj, add ) {
if ( _.isArray(obj) ) {
_.forEach( obj, function( v, i ) {
if ( /\[\]$/.test( prefix ) ) {
add( prefix, v );
} else {
buildParams( prefix + "[" + ( typeof v === "object" || _.isArray(v) ? i : "" ) + "]", v, add );
}
});
} else if ( obj != null && typeof obj === "object" ) {
_.forEach( obj, function( v, k ) {
buildParams( prefix + "[" + k + "]", v, add );
});
} else {
add( prefix, obj );
}
};
@tpai
Copy link
Author

tpai commented Jan 7, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment