AniUI Academy

Serialise params into a query string

mediumDOM & Utilities+250 XPPractice

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.

Arguments

paramsRecord<string, string | number | boolean | Array | null | undefined>
The params object. Values may be primitives or arrays; null and undefined values are omitted.

Returns

string — A URL query string without a leading ?, with keys sorted ascending so the result is canonical. "" for an empty object.

Examples

stringifyQuery({ sort: "name", page: 2 });
// => "page=2&sort=name"

Keys are sorted so the output is stable across calls.

stringifyQuery({ tag: ["a", "b"], q: "hello world" });
// => "q=hello%20world&tag=a&tag=b"

Arrays expand into one pair per element; values are percent-encoded.

stringifyQuery({ a: null, b: undefined, c: "", d: false });
// => "c=&d=false"

null/undefined drop; "" stays as key=; booleans stringify.

What it has to do

  • Sort keys ascending with the default sort so the output is canonical.
  • Skip null and undefined values but keep "" as key=.
  • Expand an array value into one pair per element, in array order; emit nothing for an empty array.
  • Encode keys and values with encodeURIComponent and join pairs with &.
  • Return the string without a leading ?, and "" when empty.

Notes

  • Canonicalising with a sort is what lets you use the query string as a cache key: { a: 1, b: 2 } and { b: 2, a: 1 } both serialise identically.
  • encodeURIComponent leaves !'()* unencoded, which is fine for URLs but can trip up strict RFC 3986 consumers. For those you can replace them manually after calling.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.