5

Say I have some data:

let data = { a: 1, b: 2, c: 3}

and I want to add that data to an existing URL:

const url = new URL('https://www.mywebsite.com')

I'd like to set all of the object's key and value parameters as that URL's searchParams without having to set or append each item directly. I want to set THE WHOLE THING as the searchParams.

I just want to pass it in / replace the existing search params somehow. I wish it went like:

const params = new URLSearchParams(data)
url.searchParams = params

or somehow

url.searchParams.set(data) // or .append(data)

buuut of course, none of those work.

I'd prefer not to go through for of loop with Object.entries(data) but I don't see another way, I'm hoping I just didn't find it yet.

Is there an easy way to set MULTIPLE key value pairs / data from an object into a URL's search params to build a new URL?

Desired outcome:

url.toString() // https://www.mywebsite.com/?a=1&b=2&c=3

1 Answer 1

15

This is the closest thing I've found to an answer, and it works.

Reassign your URL's .search to the String version of URLSearchParams, like so:

const url = new URL('https://www.example.com')
const data = { a: 1, b: 2, c: 3 }
const params = new URLSearchParams(data)
url.search = params.toString()  // Convert params to a string and add them to url search

The result:

console.log(url.toString())  // https://www.example.com/?a=1&b=2&c=3

It totally works! 🥳


Clean little function (^-^🌸)

const buildURL = (url, params) => {
  url = new URL(url)
  params = new URLSearchParams(params)
  url.search = params.toString()
  return url
}

let url = buildURL('https://example.com', {a: 1, b:2, c:3 })
console.log(url.toString()) // https://example.com/?a=1&b=2&c=3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.