javascriptnode.jsurlurl-parameters

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

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