As a JavaScript developer, you are frequently required to construct URLs with query string parameters when asynchronously calling a RESTful API via XHR. One good way to add query string parameters to the URL is by creating an object and then converting it into a query string. This method is particularly useful when you have a lot of query string parameters.

In this article, I'll show you how to turn an object into query string parameters in JavaScript. Let us say we have the following object:

const params = {
    name: 'John Doe',
    email: '',
    profession: 'Content Writer',
    age: 29

map() & join()

The simplest way to convert the above object into a query string is by using a combination of map() and join() JavaScript functions:

// convert objec to a query string
const qs = Object.keys(params)
    .map(key => `${key}=${params[key]}`)

// print query string

In the example above, the map() function iterates over all keys in the object and creates an array of strings like key=value. The join() method is then used to join them together with &.

Now if you run the above code, you should see the following output: Doe& Writer&age=29

For older browsers that do not support the latest ES6 features we are using above, you can do the following:

var qs = Object.keys(params).map(function (key) {
    return key + '=' + params[key]

URL Encoding

The object keys and values may contain spaces and special characters prohibited in the URL. Therefore, it is recommended to properly encode each key-value pair by using the encodeURIComponent() method:

const qs = Object.keys(params)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)

Here is how the output looks like now:

Take a Look at this guide to learn more about encoding URLs in JavaScript.


The URLSearchParams interface provides utility methods to work with the query string of a URL in JavaScript. You can also use it in modern browsers to convert an object into query string parameters:

const qs = new URLSearchParams(params);

You should see the following output:

Take a look at this guide to learn more about the URLSearchParams interface.

querystring module

If you are working with Node.js, you can use the native querystring module to convert an object into query string parameters as shown below:

const querystring = require('querystring');

// convert object to a query string
const qs = querystring.stringify(params);

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.