In JavaScript, there are multiple ways to convert an object to a query string. The easiest and the most direct way is to use the URLSearchParams
interface. If you need to support older browsers, use the combination of map()
and join()
methods.
URLSearchParams
The URLSearchParams
interface provides utility methods to work with the query string of a URL in JavaScript. It can be used to add, remove, and update query string parameters.
Here is an example:
const params = {
name: 'John Doe',
profession: 'Web Designer',
age: 29
}
const qs = '?' + new URLSearchParams(params).toString()
console.log(qs)
// ?name=John+Doe&profession=Web+Designer&age=29
In the above example, we passed an object to the URLSearchParams()
constructor and then called the toString()
method to get a query string. Note that the toString()
method returns a query string without the question mark.
map()
& join()
To convert an object to a query string in older browsers:
- Use the
Object.keys()
method to get all object's keys as an array. - Use the
Array.map()
method to iterate over the array. - During each iterate, use the
encodeURIComponent()
to encode the value and then return a string containing the query parameter name and value. - Use the
Array.join()
method to join all strings by an ampersand&
symbol.
The simplest way to convert the above object into a query string is by using a combination of map()
and join()
JavaScript functions:
const params = {
name: 'John Doe',
profession: 'Web Designer',
age: 29
}
const qs =
'?' +
Object.keys(params)
.map(key => `${key}=${encodeURIComponent(params[key])}`)
.join('&')
console.log(qs)
// ?name=John%20Doe&profession=Web%20Designer&age=29
querystring
module
If you are working with Node.js, use the native querystring
module to convert an object into query string parameters as shown below:
const params = {
name: 'John Doe',
profession: 'Web Designer',
age: 29
}
const querystring = require('querystring')
const qs = '?' + querystring.stringify(params)
console.log(qs)
// ?name=John%20Doe&profession=Web%20Designer&age=29
The querystring
module encodes query string parameters automatically, so you don't need to do anything.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.