-
-
Save tjmehta/9204891 to your computer and use it in GitHub Desktop.
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(''); | |
}, ''); | |
} |
const objectToQueryParams = (o = {}) => Object.entries(o) .map((p) => `${encodeURIComponent(p[0])}=${encodeURIComponent(p[1])}`) .join("&");
Refer below gist for more:
https://gist.github.com/bhaireshm
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.
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.
So handle recursive objects or arrays in the STANDARD query form
a=val&b[0]=val&b[1]=val&c=val&d[some key]=val
, here's the final function.new Number(1)
ornew String('my string')
because NO ONE should ever do that