How to convert an object to a query string using JavaScript

published: 03 Sep 2022

2 min read

How to convert an object to a query string using JavaScript

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:

  1. Use the Object.keys() method to get all object's keys as an array.
  2. Use the Array.map() method to iterate over the array.
  3. During each iterate, use the encodeURIComponent() to encode the value and then return a string containing the query parameter name and value.
  4. 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.

How to convert an object to a query string using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, nodejs, programming
Check out what's on in the tag: javascript, nodejs, programming, array