Delete empty params from query string JS

I have this query string.

"paymentMethod=1&fullname=&persona=&companyName=&countryName=&email=&totalCameras=&camerasOwned=&cameraShares=&snapmailCount=&sessionCount=&createdAtDate=&lastLoginAtDate=&telephone=&sort=created_at%7Cdesc&limit=50&page=1"

and I am trying to delete all empty params and make this into

"paymentMethod=1&sort=created_at%7Cdesc&limit=50&page=1"

I took this approach.

  let searchParams = Object.fromEntries(new URLSearchParams(queryString))
  let filteredParams = Object.fromEntries(
    Object.entries(searchParams).filter(([_, v]) => v != "")
  )
  console.log(new URLSearchParams(filteredParams).toString())
  console.log(searchParams)

But I am not sure about this, to use new URLSearchParams twice, Is it a better and right approach?

Any guidance would be thankful.

26 thoughts on “Delete empty params from query string JS”

  1. It’s less functional, but you can create a single URLSearchParams object, then iterate over it and .delete keys which have an empty value:

    const queryString = "paymentMethod=1&fullname=&persona=&companyName=&countryName=&email=&totalCameras=&camerasOwned=&cameraShares=&snapmailCount=&sessionCount=&createdAtDate=&lastLoginAtDate=&telephone=&sort=created_at%7Cdesc&limit=50&page=1"
    
    const params = new URLSearchParams(queryString);
    [...params.entries()].forEach(([key, value]) => {
      if (!value) params.delete(key);
    });
    const cleaned = String(params);
    console.log(cleaned);

    The native URLSearchParams.forEach, kind of like getElementsByClassName, is live, so you can’t .delete inside it, otherwise the next key-value pair will be skipped – thus the spreading of the .entries iterator first.

    Reply
  2. it’s safer to use query-srting package

    define your params as an object than call the stringify method and it will take care of the undefined and empty values for you

    params = {
      paymentMethod: 1,
      fullname: 'John',
      created_at: undefined,
      test: '',
    };
    
    // cleaned object will be "paymentMethod=1&fullname=John"
    const cleaned = queryString.stringify(params);
    
    
    Reply

Leave a Comment