1👍
✅
In order to do this, you would first need to iterate over your params
object and then for the array
inside the object
you would have to conditionally iterate over it too and append each array element as a separate query parameter with the same key. And for non-array items in the object, append them as usual query parameters and then return the url after removing the leading &
.
You can create a function for converting your params object
to a URL string. Here’s how the code would look like:
const params = {
id: '002',
sequence: [{ s1: 'a' }, { s2: 'b' }, { s3: 'c' }],
limit: 3
};
function convertParamsToURL(params) {
let url = '';
for (const key in params) {
if (Array.isArray(params[key])) {
params[key].forEach((item) => {
for (const itemKey in item) {
url += `&${key}=${itemKey}=${item[itemKey]}`;
}
});
} else {
url += `&${key}=${params[key]}`;
}
}
return url.substring(1);
}
const baseUrl = 'https://localhost:3000';
const queryParam = convertParamsToURL(params);
const finalUrl = `${baseUrl}?${queryParam}`;
console.log(finalUrl)
Source:stackexchange.com