It can often be useful to transform a javascript object into a query string dynamically, without necessarily knowing the properties of that object. Another good reason is to avoid concatenation for each individual parameter.
This method can be used also in javascript/typescript frameworks like: Angular, React, Svelte, etc.
This is the vanilla javascript version:
/**
* Convert an object to a query string.
*/
function toQueryString(obj) {
return o ? ('?' + Object.keys(o).reduce((a, k) => {
a.push(k + '=' + encodeURIComponent(o[k]));
return a;
}, []).join('&')) : '';
}
Typed method (for Typescript/Angular):
/**
* Convert an object to a query string.
*/
public static toQueryString(o: object): string {
return o ? ('?' + Object.keys(o).reduce((a, k) => {
a.push(k + '=' + encodeURIComponent(o[k]));
return a;
}, []).join('&')) : '';
}
You can use it simply by chaining the function call to the url string:
window.location.href = 'https://www.google.com' + toQueryString({
'token1': 'token1',
'token2': 'token2value',
'token3': 'tokenValue',
});
The result will be:
https://www.google.com?token1=token1&token2=token2value&token3=tokenValue
That’s all.
Try it at home!