Convert an Object to a Query String using JavaScript

avatar

Borislav Hadzhiev

Thu Dec 23 20212 min read

banner

Photo by Annie Spratt

Convert an Object to a Query String #

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.

index.js
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.

Note that the 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.

Note that the 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:

  1. Use the Object.keys() method to get an array of the object's keys.
  2. Use the map() method to iterate over the array.
  3. On each iteration, return a string containing the query param name and value.
  4. Join the results by an ampersand & symbol.
index.js
// ✅ 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.

index.js
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.

The function we passed to the 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.

index.js
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.

Which approach you pick is a matter of personal preference. I'd go with the 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.
Use the search field on my Home Page to filter through my more than 1,000 articles.