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 = 'https://domain.com/api';
let data = {key1: value1, key2: value2};
url = url + '?' + toQueryString(data);
// https://domain.com/api?key1=value1&key2=value2

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.

Leave a Reply

Newsletter

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

Meta Box - Creating expert WordPress custom fields and custom meta boxes in minutes! Check it out →