-
-
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(''); | |
}, ''); | |
} |
sagarpanchal
commented
Jul 16, 2019
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.
- It skips values for functions, null, undefined
- It skips keys and values for empty objects and arrays.
- It doesn't handle Number or String Objects made with
new Number(1)
ornew String('my string')
because NO ONE should ever do that
const objectToQueryString = (initialObj) => {
const reducer = (obj, parentPrefix = null) => (prev, key) => {
const val = obj[key];
key = encodeURIComponent(key);
const prefix = parentPrefix ? `${parentPrefix}[${key}]` : key;
if (val == null || typeof val === 'function') {
prev.push(`${prefix}=`);
return prev;
}
if (['number', 'boolean', 'string'].includes(typeof val)) {
prev.push(`${prefix}=${encodeURIComponent(val)}`);
return prev;
}
prev.push(Object.keys(val).reduce(reducer(val, prefix), []).join('&'));
return prev;
};
return Object.keys(initialObj).reduce(reducer(initialObj), []).join('&');
};
objectToQueryString({
name: 'John Doe',
age: 20,
children: [
{ name: 'Foo Doe' },
{ name: 'Bar Doe' }
],
wife: {
name: 'Jane Doe'
}
});
// -> name=John%20Doe&age=20&children[0][name]=Foo%20Doe&children[1][name]=Bar%20Doe&wife[name]=Jane%20Doe
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.