Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 719
aeXuser264 Avatar asked Jul 20 '20 05:07

aeXuser264


3 Answers

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());
like image 159
Rahul Bhobe Avatar answered Oct 16 '22 11:10

Rahul Bhobe


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)
});
like image 4
r712m Avatar answered Oct 16 '22 10:10

r712m


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();
like image 2
abdelgrib Avatar answered Oct 16 '22 10:10

abdelgrib