Serialise params into a query string
The reverse trip matters more than it looks: if the same set of filters can produce two different strings, your cache keys, your analytics and your React Query keys all fragment. Sorting the keys makes the output canonical.
Implement stringifyQuery(params) returning the query string **without** a leading ?. Take the object's own keys, sort them ascending with the default Array.prototype.sort comparison, and process them in that order.
Skip any entry whose value is null or undefined. An empty string is kept and renders as key=. Booleans render as true and false, numbers with String(value). An array value produces one key=value pair per element in array order, all sitting at that key's sorted position; an empty array produces nothing at all.
Encode both key and value with encodeURIComponent, join the pairs with &, and return "" when there is nothing to emit.
What it has to do
- Sort keys ascending with the default sort so the output is canonical.
- Skip
nullandundefinedvalues but keep""askey=. - Expand an array value into one pair per element, in array order; emit nothing for an empty array.
- Encode keys and values with
encodeURIComponentand join pairs with&. - Return the string without a leading
?, and""when empty.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.