Stringify query parameters
function serializeSearchParams(obj: any, prefix = ''): string {
const str = [];
let p;
for (p in obj) {
// eslint-disable-next-line no-prototype-builtins
if (obj.hasOwnProperty(p)) {
const k = prefix ? prefix + '[' + p + ']' : p;
const v = obj[p];
str.push(
v !== null && typeof v === 'object'
? serializeSearchParams(v, k)
: encodeURIComponent(k) + '=' + encodeURIComponent(v)
);
}
}
return str.join('&');
}
Why?
Normally, you'd use the qs library or URLSearchParams but if you have an object with further objects then URLSearchParams doesn't handle it well, so this function will take care of this and return a string of URI encoded params.
Usage
In this example, we've got an object called params which includes a child object called filter, as well as a branch called limit, this will be serialized so it can be properly passed, for example to a REST API.
const params = {
filter: {
slug: {
_eq: "about",
},
},
limit: 1,
};
console.log( '?' + serializeSearchParams(params) );