Data #2 — Flatten & Unflatten Nested Objects

Convert { a: { b: { c: 1 } } } to { 'a.b.c': 1 } and back. Recursive and iterative approaches with custom separator support.

9 min read
JavaScript
Data
Objects
Recursion

TABLE OF CONTENTS
Data #2 — Flatten & Unflatten Nested Objects

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.grandchild paths.
  • 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.


Let's Connect

© 2026 Naveen Karthik // Built with React & MUI