Sometimes, we’ve to do convert a JavaScript object’s data into a query string that we can use to make HTTP requests.
In this article, we’ll look at how to encode a JavaScript object into a query string.
URLSearchParams Constructor
We can use the URLSearchParams
constructor to let us create query strings easily from a JavaScript object.
It’s available with most current browsers.
For instance, we can write:
const object = {
a: 1,
b: 2,
c: undefined,
d: null
}
const queryString = new URLSearchParams(object).toString()
console.log(queryString)
We pass in the object
that we want to convert to a query string straight into the URLSearchParams
constructor.
Then we call toString
to return the query string.
And so queryString
is:
'a=1&b=2&c=undefined&d=null'
undefined
and null
are both converted to strings.
The property names are used as keys and the property values are used as the values.
We can also loop through the object and insert the query parameters with the append
method:
const object = {
a: 1,
b: 2,
c: undefined,
d: null
}
const searchParams = new URLSearchParams()
Object.keys(object).forEach(key => {
searchParams.append(key, object[key])
});
const queryString = searchParams.toString()
console.log(queryString)
We call Object.keys
to get the keys in object
.
Then we call forEach
with the key
to get the key from object
.
And then call append
to add the key and value respectively as arguments.
Then we call searchParams.toString
to return the query string.
Therefore, we get the same result as before for queryString
.
We can simply the forEach
call with the Object.entries
method to get an array of arrays of key-value pairs.
So we write:
const object = {
a: 1,
b: 2,
c: undefined,
d: null
}
const searchParams = new URLSearchParams()
Object.entries(object).forEach(([key, value]) => {
searchParams.append(key, value)
});
const queryString = searchParams.toString()
console.log(queryString)
to create the query string.
In the forEach
callback, we call append
with the key
and value
destructured from the parameter to insert the query parameters.
And so we get the same result as we have before.
Conclusion
We can encode a JavaScript object into a query string with the URLSeacrhParams
constructor available with most browsers.