Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@duncanbeevers
Created July 16, 2013 23:34
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 duncanbeevers/6016229 to your computer and use it in GitHub Desktop.
Save duncanbeevers/6016229 to your computer and use it in GitHub Desktop.
Query string from JS object
function toQueryString(obj) {
var ret = [];
function add(dest, key, val) {
var type = Object.prototype.toString.call(val), i, len;
if ("[object Array]" === type) {
// Array
for (i = 0, len = val.length; i < len; i++) { add(dest, key + "[]", val[i]); }
} else if ("[object Object]" === type) {
// Object
for (i in val) { add(dest, key + "[" + i + "]", val[i]); }
} else {
// Strings and numbers
key_to_encode = key;
value_to_encode = val;
dest.push(encodeURIComponent(key) + "=" + encodeURIComponent(val));
}
}
for (var key in obj) { add(ret, key, obj[key]); }
return ret.join("&");
}
module.exports = toQueryString;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment