I was working with query params, and got introduced to URLSearchParams
. I am using it to form this kind of object to query,
const x = {
a: 'hello World'
b: 23
c: ''
}
let params = new URLSearchParams(x);
console.log(params.toString()) // a=hello+World&b=23&c=
Here, I dont want to have that c=
, as it's ugly, and my API doesn't need that.
So, I want this result a=hello+World&b=23
(without empty query string)
But, I couldn't find anything on the MDN Web Docs.
How am I supposed to do that?
Doing the following doesn't work, as it seems to directly mutate the params
which affects the forEach
:
const x = {
a: 'hello World',
b: '',
c: ''
};
let params = new URLSearchParams(x);
params.forEach((value, key) => { // never reaches `c`
console.log(key, ' => ', value)
if (value == '')
params.delete(key);
});
console.log(params.toString());
You can iterate over the key-value pair and delete the keys with null
values:
const x = {
a: 'hello World',
b: '',
c: ''
};
let params = new URLSearchParams(x);
let keysForDel = [];
params.forEach((value, key) => {
if (value == '') {
keysForDel.push(key);
}
});
keysForDel.forEach(key => {
params.delete(key);
});
console.log(params.toString());
A clean way I do it myself is as follows (using lodash):
import omitBy from 'lodash/omitBy';
import isEmpty from 'lodash/isEmpty';
const x = {
a: 'hello World'
b: 23
c: ''
}
const params = new URLSearchParams(omitBy(x, isEmpty));
// mixing other sets
const params = new URLSearchParams({
otherParam: 'foo',
...omitBy(x, isEmpty)
});
Simple way to delete useless params from query in JavaScript ES5+:
for (let param in query) { /* You can get copy by spreading {...query} */
if (query[param] === undefined /* In case of undefined assignment */
|| query[param] === null
|| query[param] === ""
) {
delete query[param];
}
}
return new URLSearchParams(query).toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With