Passing array into URLSearchParams while consuming http call for get request
If you want to use @washington-braga's approach but don't want to install lodash:
function buildParams(data) {
const params = new URLSearchParams()
Object.entries(data).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach(value => params.append(key, value.toString()))
} else {
params.append(key, value.toString())
}
});
return params.toString()
}
In fact, you can't pass an array directly but you can use several times the append
method:
let params = new URLSearchParams();
params.append('arrayparams', 'val1');
params.append('arrayparams', 'val2');
params.append('arrayparams', 'val3');
console.log(params.toString());
URLSearchParams can be passed a sequence of pairs, so to have an array of values:
var ids = [1,2,3,4]
var search = new URLSearchParams(ids.map(s=>['id',s]))
var searchString = search.toString()
// "id=1&id=2&id=3&id=4"
// To get the ids from the URL search string
var search_ids = [...search.getAll('id')]