Last active
January 7, 2016 02:09
-
-
Save tpai/31ef91ff6643d38abea5 to your computer and use it in GitHub Desktop.
$.param() => _.param()
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
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 ); | |
} | |
}; |
Author
tpai
commented
Jan 7, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment