Introduction
In this lab, we will explore how to convert a query string or URL into an object using JavaScript. We will use the String.prototype.split() method to extract the parameters from the URL, then create an object using the URLSearchParams constructor and convert it into an array of key-value pairs. Finally, we will use Array.prototype.reduce() to convert the array into a JavaScript object. This lab will help you understand how to manipulate and extract data from URLs and query strings in JavaScript.
Converting Query String to Object
To convert a query string or URL to an object, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
String.prototype.split()to extract the parameters from the givenurl. - Use the
URLSearchParamsconstructor to create an object and convert it to an array of key-value pairs using the spread operator (...). - Use
Array.prototype.reduce()to convert the array of key-value pairs into an object.
Here is the code to convert the query string:
const queryStringToObject = (url) =>
[...new URLSearchParams(url.split("?")[1])].reduce(
(a, [k, v]) => ((a[k] = v), a),
{}
);
Example usage:
queryStringToObject("https://google.com?page=1&count=10");
// {page: '1', count: '10'}
Summary
Congratulations! You have completed the Query String to Object lab. You can practice more labs in LabEx to improve your skills.