JavaScript: How to convert an object to a query string

javascript object to 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 thought on “JavaScript: How to convert an object to a query string

  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.


Subscribe to our newsletter to receive news and tutorials about WordPress and web development.

Meta Box - Create advanced WordPress custom fields and custom meta boxes with ease Download Now