Parse bracket-notation query parameters
Once filters get nested, flat key-value parsing is not enough: APIs and form libraries encode structure into the key itself with bracket notation. Rebuilding the object from that is a neat exercise in walking a path and creating containers as you go.
Implement parseNestedQuery(search) returning a nested plain object. Strip one leading ?, split on &, and skip empty segments. Split each segment on its first =; a segment with no = has the value "".
Read the bracket structure from the **raw** key before decoding: the text before the first [ is the base key, and each following [...] is one more path segment. Then decode each segment and the value individually by replacing + with a space and calling decodeURIComponent, falling back to the raw text if that throws — so a percent-encoded bracket never changes the structure.
An empty segment [] means append to an array, so tags[]=a&tags[]=b gives { tags: ["a", "b"] }. Every other segment, **including a numeric one**, is an ordinary object key, so a[0]=x gives { a: { "0": "x" } }. Containers are created as you walk: a segment is an array when the next segment is [] and a plain object otherwise, and if a [] is followed by further segments a new object is appended for each pair. A repeated non-array key is overwritten, so the last value wins. An empty input returns {}.
What it has to do
- Strip an optional leading
?, split on&, and skip empty segments. - Read the bracket path from the raw key, then decode each key segment and the value separately, handling
+as a space. - Append to an array for the empty
[]segment. - Treat every other segment, including numeric ones, as an ordinary object key.
- Create arrays and objects on demand while walking the path, and return
{}for empty input.
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.