Explain Codes LogoExplain Codes Logo

How to serialize an Object into a list of URL query parameters?

javascript
prompt-engineering
url-serialization
javascript-objects
Alex KataevbyAlex Kataev·Jan 19, 2025
TLDR

Quickly serialize an object to query parameters with a simple, but mighty JavaScript one-liner, utilizing Object.entries() to iterate and URLSearchParams for formatting.

const objectToQuery = obj => new URLSearchParams(Object.entries(obj)).toString(); const queryString = objectToQuery({name: 'John', age: 30}); // "name=John&age=30"

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!

// This is like a detergent for your object, washing away `null` and `undefined` values const cleanObject = obj => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null)); const objectToQuery = obj => new URLSearchParams(cleanObject(obj)).toString();

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.

// jQuery whispering sweet nothings to your object const queryString = $.param({ name: 'John', age: 30, hobbies: ['reading', 'gaming'] }); // "name=John&age=30&hobbies[]=reading&hobbies[]=gaming"

Manual serialization

Feeling like going barebones ‒ no dependencies, just pure JavaScript? Here's how you can serialize manually using encodeURIComponent():

// URL assembly language - the DIY way const serialize = obj => Object.keys(obj).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}` ).join('&'); const queryString = serialize({name: 'John', age: 30}); // "name=John&age=30"

Empty string exclusion

Your URL doesn’t need to carry that extra luggage of empty string values. Lighten the load!

// It's like a diet for your object, trimming away those empty string fats const cleanObject = obj => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v !== '')); const objectToQuery = obj => new URLSearchParams(cleanObject(obj)).toString();

Nested structures handling

What about heavier luggage like nested objects and arrays? They need some unpacking before getting onto the URLSearchParams conveyor belt.

// The flat earth society approves this function function serializeComplexObj(object, prefix = '') { const pairs = []; for (const [key, value] of Object.entries(object)) { if (typeof value === 'object' && value !== null) { pairs.push(...serializeComplexObj(value, `${prefix}${key}.`)); } else { pairs.push([`${prefix}${key}`, value]); } } return pairs; } const objectToQuery = obj => new URLSearchParams(serializeComplexObj(obj)).toString();