How to serialize an Object into a list of URL query parameters?
Quickly serialize an object to query parameters with a simple, but mighty JavaScript one-liner, utilizing Object.entries()
to iterate and URLSearchParams
for formatting.
Don't forget that encodeURIComponent
is your friend when dealing with URL-safe characters!
Scalar null and undefined values
Watch out for those null
's and undefined
's! These silent killers could sneak into your query strings as nasty little strings "null"
or "undefined"
. Better to exclude these right from the start!
Tackling browser compatibility
Is URLSearchParams
acting weird? Well, my friend, it's time to have a word with those good old browser compatibility issues. While URLSearchParams
is a modern browser celeb, some oldies might not recognize this star. Consider a polyfill for such cases.
jQuery alternate approach
Are you a jQuery fan or stuck with legacy browsers? Don't fret, jQuery’s $.param()
has your back. It's like URLSearchParams
but with some make-up on to make it look fancy.
Manual serialization
Feeling like going barebones ‒ no dependencies, just pure JavaScript? Here's how you can serialize manually using encodeURIComponent()
:
Empty string exclusion
Your URL doesn’t need to carry that extra luggage of empty string values. Lighten the load!
Nested structures handling
What about heavier luggage like nested objects and arrays? They need some unpacking before getting onto the URLSearchParams
conveyor belt.
Was this article helpful?