Home > other >  How to add JavaScript object as a URL's searchParams without looping
How to add JavaScript object as a URL's searchParams without looping

Time:09-19

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

CodePudding user response:

No, this cannot be done. Here's why:

You can create a new URLSearchParams object like this: (reference)

let data = { a: 1, b: 2, c: 3}
const params = new URLSearchParams(data);
console.log(params.get('a')) // => 1

However, you cannot assign this object to an existing URL object because the .searchParams property is read-only (reference). Furthermore, there is no constructor to create a URL object from an existing URLSearchParams object. There might be a good reason, but there's none that I know of.

Because of this, your best solution is just to use a for of loop.

CodePudding user response:

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
console.log(url.toString())  // https://www.example.com/?a=1&b=2&c=3
  • Related