buildQuery.js
Build a query string from an object of data.
Example
let petfinderData = {
key: '12345',
shelterID: 'abc00',
count: 20,
animals: ['dogs', 'cats']
};
// returns "key=12345&shelterID=abc00&count=20&animals=dogs%2Ccats"
let query = buildQuery(petfinderData);
The helper function
/**
* Build a query string from an object of data
* (c) Chris Ferdinandi, MIT License, https://gomakethings.com
* @param {Object} data The data to turn into a query string
* @return {String} The query string
*/
function buildQuery (data) {
return new URLSearchParams(data).toString();
}
How it works
The URLSearchParams()
method was built specifically for creating and manipulating query string data.
To create a URLSearchParams
object, we can use the new URLSearchParams()
constructor, passing in our data object as an argument.
let query = new URLSearchParams(petfinderData);
Once you have a URLSearchParams
object, you can use a variety of methods to get and add values to the data, if needed.
In our case, we just need to get a query string, which we can do with the URLSearchParams.toString()
method.
This automatically encodes any data in our object for us, and returns a query string.
let query = new URLSearchParams(petfinderData);
// returns "key=12345&shelterID=abc00&count=20&animals=dogs%2Ccats"
let queryString = query.toString();