'How to remove empty query params using URLSearchParams?

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());


Solution 1:[1]

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());

Solution 2:[2]

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)
});

Solution 3:[3]

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();

Solution 4:[4]

In case your are working with the query as a string you can also filter it with a regex :

const query = "a=hello+World&b=23&c=&d=12&e="

query.replace(/\w+=&/g, '').replace(/&\w+=$/, '')
// "a=hello+World&b=23&d=12"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Audwin Oyong
Solution 2 r712m
Solution 3 Audwin Oyong
Solution 4 Lucas David