Convert Object to Query String and vice versa in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
5 min

banner

# Table of Contents

  1. Convert an Object to a Query String in JavaScript
  2. Convert a Query String to an Object in JavaScript

# Convert an Object to a Query String in JavaScript

Use the URLSearchParams() constructor to convert an object to a query string.

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"

convert object to query string

The code for this article is available on GitHub

If you need to convert a query string to an object, click on the following subheading.

We passed an object to the URLSearchParams() constructor and called the toString() method on the result.

The URLSearchParams class returns an object that is used to work with the query string of a URL.

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

# Convert an Object to a Query String using Object.keys()

This is a four-step process:

  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 with an ampersand & symbol.
index.js
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"

convert object to query string using object keys

The code for this article is available on GitHub

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 only argument the Array.join() method takes is a separator - the string used to separate the elements of the array.

The last step is to prepend a question mark to the result to form a valid query string.

# Convert a Query String to an Object in JavaScript

Use the URLSearchParams constructor to convert a query string to an object.

The constructor returns an object instance from which we can access the query string parameters using the get() method, e.g. obj.get('page').

index.js
const queryString = '?page=3&filter=js'; const obj = new URLSearchParams(queryString); // โœ… Get query parameters from the object console.log(obj.get('page')); // ๐Ÿ‘‰๏ธ "3" console.log(obj.get('filter')); // ๐Ÿ‘‰๏ธ "js" // โœ… Check if object contains query parameter console.log(obj.has('page')); // ๐Ÿ‘‰๏ธ true console.log(obj.has('test')); // ๐Ÿ‘‰๏ธ false // โœ… Set new query parameters on the object obj.set('limit', 10); console.log(obj.get('limit')); // ๐Ÿ‘‰๏ธ "10" // โœ… Get the Query String equivalent of the object // ๐Ÿ‘‡๏ธ "page=3&filter=js&limit=10" console.log(obj.toString());

convert query string to object

The code for this article is available on GitHub

You can use the window.location.search property to get the query string that has to be passed to the URLSearchParams constructor.

index.js
const obj = new URLSearchParams(window.location.search); console.log(obj.get('page')); // ๐Ÿ‘‰๏ธ "3" console.log(obj.get('filter')); // ๐Ÿ‘‰๏ธ "js"

The search property returns a string containing a ? followed by the parameters of the URL, e.g. ?page=123.

The URLSearchParams class takes a query string as a parameter, but if you have an entire URL, you can use this approach instead.

index.js
const url = new URL('https://bobbyhadz.com?page=3&filter=js'); const obj = new URLSearchParams(url.search); console.log(obj.get('page')); // ๐Ÿ‘‰๏ธ "3" console.log(obj.get('filter')); // ๐Ÿ‘‰๏ธ "js"

The URL() constructor returns a newly created URL object that represents the URL it got passed as a parameter.

# Converting the URLSearchParams object to a native JS Object

If you want to convert the URLSearchParams object to a native JavaScript object, pass the object instance to the Object.fromEntries method.

index.js
// โœ… If you have Query String const queryString = '?page=3&filter=js'; const obj1 = Object.fromEntries( new URLSearchParams(queryString), ); // ๐Ÿ‘‡๏ธ {page: '3', filter: 'js'} console.log(obj1); // ---------------------------------------------------- // โœ… If you have entire URL const url = new URL('https://example.com?page=3&filter=js'); const obj2 = Object.fromEntries(new URLSearchParams(url.search)); // ๐Ÿ‘‡๏ธ {page: '3', filter: 'js'} console.log(obj2);

convert urlsearchparams object to native js object

The code for this article is available on GitHub

However, you probably don't need to convert the return value of the URLSearchParams constructor to a native object as it implements many convenient methods.

# Get the value of a query parameter

The URLSearchParams.get method takes the name of the query parameter and returns the corresponding value if the parameter is found, otherwise null is returned.

index.js
const obj = new URLSearchParams(window.location.search); console.log(obj.get('page')); // ๐Ÿ‘‰๏ธ "3" console.log(obj.get('filter')); // ๐Ÿ‘‰๏ธ "js"

Note that the value returned from the get() method has a type of string.

If you need to convert the value to a number, you can pass it to the Number() constructor, e.g. const pageNum = Number(page);.

# Check if a query parameter exists

If you need to check whether the query parameter is contained in the object, you can use the URLSearchParams.has method.

index.js
const obj = new URLSearchParams(window.location.search); console.log(obj.has('page')); // ๐Ÿ‘‰๏ธ true console.log(obj.has('test')); // ๐Ÿ‘‰๏ธ false

The method takes the name of the parameter and returns true if the parameter is present and false otherwise.

# Adding query parameters to the object

You can use the URLSearchParams.set method if you need to add query parameters to the object.

index.js
const obj = new URLSearchParams(window.location.search); obj.set('limit', 10); console.log(obj.get('limit')); // ๐Ÿ‘‰๏ธ "10"

The set() method takes 2 parameters:

  • the name of the parameter to set
  • the value of the parameter

# Getting the query string from the object

When you need to get the equivalent query string, you just need to call the URLSearchParams.toString() method.

index.js
const obj = new URLSearchParams(window.location.search); // ๐Ÿ‘‡๏ธ page=123&limit=10 console.log(obj.toString());

Note that the toString() method returns a query string without the question mark.

You would probably have to add the question mark if appending the result to a URL.

index.js
const obj = new URLSearchParams(window.location.search); // ๐Ÿ‘‡๏ธ "page=3&filter=js&limit=10" console.log(obj.toString()); const withQuestionMark = '?' + obj.toString(); // ๐Ÿ‘‡๏ธ "?page=2&filter=js&limit=10" console.log(withQuestionMark);

The object that the URLSearchParams() constructor returns implements many of the commonly used array methods, e.g. keys(), values() and forEach().

index.js
const queryString = '?page=3&filter=js'; const obj = new URLSearchParams(queryString); const keys = obj.keys(); console.log(keys); // ๐Ÿ‘‰๏ธ (iterator) {'page', 'filter'} const values = obj.values(); console.log(values); // ๐Ÿ‘‰๏ธ (iterator) {'3', 'js'}
The code for this article is available on GitHub

# Iterating over the URLSearchParams object

If you need to iterate over the object, use the URLSearchParams.forEach method.

index.js
const queryString = '?page=3&filter=js'; const obj = new URLSearchParams(queryString); obj.forEach((value, key) => { console.log(value); // ๐Ÿ‘‰๏ธ "3", "js" console.log(key); // ๐Ÿ‘‰๏ธ "page", "filter" });
The code for this article is available on GitHub

The forEach method takes a function and invokes it for every key-value pair in the object of query parameters.

The first parameter the function is passed is the value and the second is the key of the query parameter.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev