JavaScript: How to convert an object to a query string

Converting an object to a query string is a very common task in JavaScript. It allows you build your URL for ajax requests quicker and easier. Although there’s no native way to do this, you can complete this task with a simple code. See below.

function toQueryString(obj) {
    return Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&');

Now you can use it in you JavaScript code like this:

let url = '';
let data = {key1: value1, key2: value2};
url = url + '?' + toQueryString(data);

1 comment

  1. Great information. Since last week, I am gathering details about javascript experience. There are some amazing details on your blog which I didn’t know. Thanks.

Comments are closed.