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

Leave a Reply

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