Sometimes, we want to convert a JavaScript object to a query string.
In this article, we’ll look at how to convert a JavaScript object to a query string.
How to convert a JavaScript object to a query string?
To convert a JavaScript object to a query string, we can use the Object.entries method and some array methods.
For instance, we write:
const obj = {
foo: "22",
bar: "23434"
};
const queryString = Object.entries(obj)
.map(([key, value]) => {
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
})
.join('&')
console.log(queryString)
to call Object.entries with obj to convert obj to an array of key-value pair arrays.
Then we call map with a callback to combine the key and value into a query parameter string.
Next, we call join with '&' to join the query parameters together.
As a result, queryString is 'foo=22&bar=23434'.
Conclusion
To convert a JavaScript object to a query string, we can use the Object.entries method and some array methods.