Last active
August 29, 2015 14:01
-
-
Save rockymanobi/590c3a10f1ece46a653f to your computer and use it in GitHub Desktop.
Espruino, build query string from object
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
function queryString( a ) { | |
var prefix, | |
s = [], | |
add = function( key, value ) { | |
value = value === null ? "" : value; | |
s[ s.length ] = key + "=" + value; | |
}; | |
var buildParams = function( prefix, obj, add ) { | |
var name; | |
if ( Array.isArray( obj ) ) { | |
obj.forEach( function( v, i ) { | |
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, add ); | |
}); | |
} else if ( typeof obj === "object" ) { | |
for ( name in obj ) { | |
buildParams( prefix + "[" + name + "]", obj[ name ], add ); | |
} | |
} else { | |
// Serialize scalar item. | |
add( prefix, obj ); | |
} | |
}; | |
if ( Array.isArray( a )) { | |
a.forEach( function( value, key) { | |
add( key, value ); | |
}); | |
} else { | |
for ( prefix in a ) { | |
buildParams( prefix, a[ prefix ], add ); | |
} | |
} | |
return s.join( "&" ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Description
A function that builds query string from objects like jQuery#param function does.
The output value will be like
arg1=1&arg2=hoge&arr[]=text&arr[]=22&arr[]=44
.Usage