javascripturlurl-parametersquery-string

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(([_, value]) => value != "")
)
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.


Solution

  • 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 to a new array.