Last active
October 31, 2024 23:25
-
-
Save tjmehta/9204891 to your computer and use it in GitHub Desktop.
Object to Querystring - JavaScript, JS, JSON
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
function objectToQuerystring (obj) { | |
return Object.keys.reduce(function (str, key, i) { | |
var delimiter, val; | |
delimiter = (i === 0) ? '?' : '&'; | |
key = encodeURIComponent(key); | |
val = encodeURIComponent(obj[key]); | |
return [str, delimiter, key, '=', val].join(''); | |
}, ''); | |
} |
Great 🔥 💯
const objectToQuerystring = obj => new URLSearchParams(obj).toString();
lol
const objectToQuerystring = obj => new URLSearchParams(obj).toString();
lol
That doesn't work with objects that contain arrays or other objects.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i created a gist for to recursively encode and decode querystrings (encode = object to querystring, decode = querystring to object).
Feel free to copy/paste this in your own projects.
Thanks @darkylmnx (his answer) for your encode function. I added the corresponding decode function (both in typescript format).
I tested the code by creating an complex object, encoding it to a querystring and decoding it to an object, then i compared the input object with the decoded output object.