Introduction
In this lab, we will explore how to generate a query string from the key-value pairs of an object using JavaScript. We will use the Array.prototype.reduce() method on Object.entries() to create the query string and determine the appropriate symbol to be used based on the length of the queryString. By the end of this lab, you will be able to efficiently generate a query string for your web applications.
Converting Object to Query String
To convert an object to a query string, use objectToQueryString() function which generates a query string from the key-value pairs of the given object.
The function works as follows:
- It uses
Array.prototype.reduce()onObject.entries()to create the query string fromqueryParameters. - It determines the
symbolto be either?or&based on the length ofqueryString. - It concatenates
valtoqueryStringonly if it's a string. - It returns the
queryStringor an empty string when thequeryParametersare falsy.
Here's the code for objectToQueryString() function:
const objectToQueryString = (queryParameters) => {
return queryParameters
? Object.entries(queryParameters).reduce(
(queryString, [key, val], index) => {
const symbol = queryString.length === 0 ? "?" : "&";
queryString +=
typeof val === "string" ? `${symbol}${key}=${val}` : "";
return queryString;
},
""
)
: "";
};
Example usage of objectToQueryString() function:
objectToQueryString({ page: "1", size: "2kg", key: undefined }); // returns '?page=1&size=2kg'
Summary
Congratulations! You have completed the Object to Query String lab. You can practice more labs in LabEx to improve your skills.