Reputation: 4210
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
Upvotes: 5
Views: 3947
Reputation: 4210
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! 🥳
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
Upvotes: 14