Skip to content

Instantly share code, notes, and snippets.

@evaisse
Last active October 19, 2017 00:09
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save evaisse/3e93a455dc9c6b1b9926 to your computer and use it in GitHub Desktop.
Object.toQueryString - Vanilla JS version - encode object to POST, GET AJAX calls
/**
* Simply encode a base js object as {a:2, d:[1,"two"], c: {foo: {bar:1}}}
* And returns URL encoded string : a=2&d[0]=1&d[1]=two&c[foo][bar]=1"
*
* @param {Object} object A base javascript object : {}
* @param {String} base Optionnal base notation, should only be used by recursion for internal work
* @return {String} URL encoded query string
*/
Object.toQueryString = function (object, base) {
var queryString = [];
Object.keys(object).forEach(function (key) {
var result,
value;
value = object[key];
if (base) {
key = base + '[' + key + ']';
}
switch (typeof value) {
case 'object':
result = Object.encodeToQueryString(value, key);
break;
case 'array':
var qs = {};
value.forEach(function (val, i) {
qs[i] = val;
});
result = Object.encodeToQueryString(qs, key);
break;
default:
result = key + '=' + encodeURIComponent(value);
}
if (value != null) {
queryString.push(result);
}
});
return queryString.join('&');
};
@racztiborzoltan
Copy link

small typo: all encodeToQueryString replace to toQueryString

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