Flattening converts a deeply nested object like { a: { b: { c: 1 } } } into { "a.b.c": 1 }. Unflattening reverses the process. This is a common coding interview question and has real uses in form libraries, URL parsers, and configuration systems.
Prerequisites: Recursion Patterns
1. Flatten an Object — Recursive Approach
Loading editor...
Note: arrays are treated as leaf values — we don't flatten inside them by default.
2. Flatten with Configurable Separator and Array Handling
Loading editor...
3. Unflatten — Convert Flat Keys Back to Nested Objects
Loading editor...
4. Iterative Flatten — Stack-Safe for Deep Objects
Loading editor...
5. Real-World Use — Form Data to Nested Payload
Many form libraries represent "user.address.city" as a flat key. Unflatten it before sending to the API:
Loading editor...
Key Takeaways
- Flatten recursively collects nested keys into
parent.child.grandchildpaths. - Unflatten splits keys by separator and builds nested objects — handle numeric keys as array indices.
- Arrays can be kept as-is or flattened by index depending on the use case.
- The iterative approach with a stack avoids call stack overflow for deeply nested objects.
- This pattern is used in: form libraries, configuration merging, URL query parsers, and database ORMs.
Next: Async #1 — The Event Loop in Depth — call stack, microtask queue, macrotask queue, and the complete execution model of JavaScript.
