Object.toQueryString - Vanilla JS version - encode object to POST, GET AJAX calls
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
/** | |
* 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('&'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
small typo: all
encodeToQueryString
replace totoQueryString