Sometimes, we want to convert the key-value pairs of a JavaScript object into a query string with the key-value pairs in the object as query parameters.
In this article, we’ll look at how to serialize an object into a list of URL query parameters with JavaScript.
Use the URLSearchParams Constructor
We can use the URLSearchParams constructor that’s available with most modern browsers to convert a JavaScript object into a query string.
For instance, we can write:
const obj = {
param1: 'something',
param2: 'somethingelse',
param3: 'another'
}
const url = new URL(`http://example.com`);
url.search = new URLSearchParams(obj);
console.log(url.toString())
to create the obj Object that we want to convert to a query string with the key-value pairs being added to the query string.
We then create the url object with the URL to create the URL instance.
Next, we set the url.search property to the query string we want to set.
To create the query string, we use the URLSearchParams constructor with obj to create the query string object. The query string will be appended to the URL when we convert it to a string.
In the last line, we call toString to convert the URL instance to a URL string.
As a result, the console log should log:
http://example.com/?param1=something¶m2=somethingelse¶m3=another
Conclusion
We can serialize a JavaScript object into a query string with the URLSearchParams constructor.