-
-
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(''); | |
}, ''); | |
} |
Should be
function objectToQuerystring (obj) {
return Object.keys(obj).reduce(function (str, key, i) {
var delimiter, val;
delimiter = (i === 0) ? '?' : '&';
key = encodeURIComponent(key);
val = encodeURIComponent(obj[key]);
return [str, delimiter, key, '=', val].join('');
}, '');
}
It wont work on nested Object like this one:
var data = {
"_id": "5973782bdb9a930533b05cb2",
"isActive": true,
"balance": "$1,446.35",
"age": 32,
"name": "Logan Keller",
"email": "[email protected]",
"phone": "+1 (952) 533-2258",
"friends": [{
"id": 0,
"name": "Colon Salazar"
},
{
"id": 1,
"name": "French Mcneil"
},
{
"id": 2,
"name": "Carol Martin"
}
],
"favoriteFruit": "banana"
};
const serialize = obj => Object.keys(obj).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])).join('&');
function objectToQuerystring (obj) {
return Object.keys(obj).reduce(function (str, key, i) {
var delimiter, val;
delimiter = (i === 0) ? '?' : '&';
key = encodeURIComponent(key);
val = encodeURIComponent(obj[key]);
return [str, delimiter, key, '=', val].join('');
}, '');
}
With array support:
function objectToQuerystring (obj) {
return Object.keys(obj).filter((key) => obj[key] != undefined && obj[key] != '').reduce((str, key, i) => {
var delimiter: string, val;
delimiter = (i === 0) ? '?' : '&';
if(Array.isArray(obj[key])) {
key = encodeURIComponent(key);
var arrayVar = obj[key].reduce((str, item) => {
val = encodeURIComponent(JSON.stringify(item));
return [str, key, '=', val, '&'].join('');
}, '');
return [str, delimiter, arrayVar.trimRightString('&')].join('');
} else {
key = encodeURIComponent(key);
val = encodeURIComponent(JSON.stringify(obj[key]));
return [str, delimiter, key, '=', val].join('');
}
}, '');
key = encodeURIComponent(key);
var arrayVar = obj[key].reduce((str, item) => {
After the assignment key = encodeURIComponent(key), obj[key] in the second line may not work as intended. Here is an improved version:
const objectToQuerystring = (obj) => {
const sp = new URLSearchParams();
Object.keys(obj).filter((key) => obj[key] != undefined && obj[key] != '').forEach(key => {
const ekey = encodeURIComponent(key);
if(Array.isArray(obj[key])) {
obj[key].forEach(val => {
sp.append(ekey, encodeURIComponent(JSON.stringify(val)));
});
} else {
sp.append(ekey, encodeURIComponent(JSON.stringify(obj[key])));
}
});
return "?"+sp.toString();
}
this check for object/string/boolean/string
serialize(params: any) {
const result = [];
if (Object.keys(params).length > 0) {
for (const key in params) {
if (params.hasOwnProperty(key)) {
const keyValue = params[key];
if (keyValue !== null) {
switch (keyValue.constructor.name) {
case 'Array':
if (keyValue.length > 0) {
const joined_value = keyValue.join(',');
result.push(`${encodeURIComponent(key)}=${encodeURIComponent(joined_value)}`);
}
break;
case 'Object':
(<any>Object).entries(keyValue).map(([k, v]: [string, any]) => {
if (v) {
result.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
}
});
break;
default:
result.push(`${encodeURIComponent(key)}=${encodeURIComponent(keyValue)}`);
}
}
}
}
return result.join('&');
} else {
return result;
}
}
@gerardcarbo you have 3 mistakes in your function
var delimiter: string, val;
=>var delimiter, string, val;
- There is no
trimRightString
buttrimRight
is correct - You forgot closing
}
at the end
Also array values in query string should be handled like this: ?arg[]=1&arg[]=2
export const toQueryString = object =>
'?' +
Object.keys(object)
.map(key => `${key}=${object[key].toString()}`)
.join('&');
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.
thank u