Borislav Hadzhiev
Thu Dec 23 2021·2 min read
Photo by Annie Spratt
Use the URLSearchParams()
constructor to convert an object to a query
string, e.g. new URLSearchParams(obj).toString()
. Calling the toString()
method on the result returns a query string without the question mark. If the
provided object is empty, an empty string is returned.
const obj = { page: 2, limit: 10, filter: 'js', }; const result = '?' + new URLSearchParams(obj).toString(); console.log(result); // 👉️ "?page=2&limit=10&filter=js"
We passed an object to the URLSearchParams() constructor to and called the toString() method on the result.
toString()
method returns a query string without the question mark.We used the addition (+) operator to prepend a question mark to the result to make it a valid query string.
URLSearchParams()
constructor is not supported in Internet Explorer. If you need to support the browser, use the combination of the map
and join
methods instead.To convert an object to a query string:
Object.keys()
method to get an array of the object's keys.map()
method to iterate over the array.&
symbol.// ✅ Supported in IE const obj = { page: 2, limit: 10, filter: 'js', }; const str = '?' + Object.keys(obj) .map(key => { return `${key}=${encodeURIComponent(obj[key])}`; }) .join('&'); console.log(str); // 👉️ "?page=2&limit=10&filter=js"
The Object.keys method returns an array of the object's keys.
const obj = { page: 2, limit: 10, filter: 'js', }; // 👇️ ['page', 'limit', 'filter'] console.log(Object.keys(obj));
The next step is to use the Array.map method to iterate over the array of keys.
map()
method gets called with each element in the array.On each iteration, we return a string in the form of key=value
.
We used the encodeURIComponent() function to encode the query parameter values.
This basically replaces characters like ?
, =
, &
with escape sequences to
produce a more consistent query string.
We used the Array.join method to join the array of strings with an ampersand separator.
const arr = ['page=2', 'limit=10', 'filter=js']; // 👇️ "page=2&limit=10&filter=js" console.log(arr.join('&'));
The last step is to prepend a question mark to the result to form a valid query string.
URLSearchParams()
constructor as it is more direct and easier to read. If you need to support some of the older browsers, the combination of map
and join
gets the job done.