Last active
January 20, 2023 23:42
-
-
Save surgiie/8f00d94c555f5926edab51fc12e1e0c2 to your computer and use it in GitHub Desktop.
Javascript function to recursively build a query string from an object.
This file contains hidden or 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
/** | |
* Variation of https://gist.github.com/luk-/2722097 | |
*/ | |
function toQueryString(obj, recursiveKey) { | |
if(obj == null || typeof obj !== "object"){ | |
return ""; | |
} | |
let keys = Object.keys(obj); | |
if (keys.length == 0) { | |
return ""; | |
} | |
let key; | |
let query; | |
let value = ""; | |
let output = []; | |
let pattern = /[!'()*]/g; | |
keys.forEach(k=>{ | |
value = obj[k] | |
key = k.toString().replace(/[!'()*]/g, escape); | |
recursiveKey ? (key = recursiveKey + "[" + key + "]") : ""; | |
if (typeof value === "object" && value != null) { | |
query = toQueryString(value, key); | |
if(query){ | |
output.push(query); | |
} | |
} else if(value != null) { | |
output.push( | |
key + "=" + value.toString().replace(pattern, escape) | |
); | |
} | |
}); | |
return output.join("&"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment