Skip to content

Instantly share code, notes, and snippets.

@rockymanobi
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rockymanobi/590c3a10f1ece46a653f to your computer and use it in GitHub Desktop.
Save rockymanobi/590c3a10f1ece46a653f to your computer and use it in GitHub Desktop.
Espruino, build query string from object
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( "&" );
}
@rockymanobi
Copy link
Author

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

var a = { hoge: 1, aba: "piyo", arr: ["ab",3, 4], eee: "1" };
queryString( a );
// arg1=1&arg2=hoge&arr[]=text&arr[]=22&arr[]=44

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