I love both previous suggestions! However, if you’re trying to send the data over a network or work with URLs, you might want to javascript convert object to string into a query-string format. Here’s a neat trick for that:
function toQueryString(obj) {
return Object.keys(obj)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
.join('&');
}
var o = { a: 1, b: 2 };
console.log('Query format: ' + toQueryString(o)); // Output: Query format: a=1&b=2
This method is particularly helpful when you need to work with query strings for HTTP requests, form submissions, or even debugging. It provides a compact string format that is easy to pass around in URLs or APIs.