Query-string encoding of a JavaScript object
For quick and easy query-string encoding of a JavaScript object, serialize the object using encodeURIComponent
to ensure it's properly URL encoded:
This one-liner creates a URL safe query-string by pairing keys with values.
Encoding complex objects
This method works well for flat JavaScript objects. However, when dealing with nested or complex objects, additional steps are needed to handle nested properties or arrays.
In this case, we create a serialize
function which makes use of recursion to walk the object's properties, creating a properly encoded query-string:
URLSearchParams: Upgrade your code
For a more advanced solution, URLSearchParams
is a modern API that simplifies preparing a query-string. It automatically encodes the elements and is highly recommended where support is not an issue.
Encoding corner cases
To address special cases and efficiently encode complex objects, it's beneficial to have more flexible solutions like using Object.entries()
which allows for handling both simple objects and complex structures, let's see how:
Dealing with potential issues
Special characters and encoding
Say you have special characters in values. Using encodeURIComponent
ensures they are properly encoded:
This will encode them so they don't disrupt the query-string.
Encoding dates and other non-string values
Objects may contain non-string values like Date objects, which must be converted to strings before encoding:
This method converts the date to an UTC string and encodes it.
Reusability and practicality
When scaling to enterprise level, encapsulating the query-string encoding functionality in a separate module encourages code reuse and simplifies maintenance:
This way, anyone can import these functions and use them across projects.
References
Was this article helpful?