How to remove empty query params using URLSearchParams?
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)
});
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());