For conversion of an object to a query string, use the following methods:
- toString() method of the URLSearchParams() constructor
- Object.keys() method with map() and join() methods
Let’s examine these methods individually!
Method 1: Conversion of an Object to a Query String Using toString() Method of the URLSearchParams() Constructor
Follow the given syntax for “URLSearchParams” interface:
Here, pass the “object” to the constructor of the “URLSearchParams” interface, which will convert the key-value pairs into a string using the “toString()” method.
A string containing a query string valid for insertion in a URL is returned by the “URLSearchParams().toString()” method.
Create an object with properties “name”, “age”, and “email”:
Call the toString() method with URLSearchParams() constructor by passing the object as an argument to the constructor and store the result in the variable “objString”:
Print the string on the console using the “console.log()” method:
The output shows that the object is successfully converted to the string.
Method 2: Conversion of an Object to a Query String Using Object.keys() Method with map() and join() Methods
Another approach to convert an object to a string is the “Object.keys()” method with “map()” and “join()” methods. The “Object.keys()” method is used to retrieve the array of object’s keys. The “map()” method is used for iterating over the array, and the “join()” method is used to join all the results by an ampersand “&“symbol.
Use the below lines of code for converting an object to a query string:
In the above code:
- First, get the keys of the object using the “Object.keys()” method.
- Then, iterate over the array of keys using the “map()” method.
- Use the “encodeURIComponent()” method to encode the query parameter values.
- Finally, join all the results using the “join()” method by an ampersand “&” symbol.