Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Flatten a Nested Object

Data Structures, Operators & Stringshard

Implement `flattenObject(obj)` that returns a new object with no nesting: each leaf value is keyed by its full dot-separated path. Nested plain objects are flattened; arrays and primitive values are treated as leaves (kept as-is).

Examples

Input: { a: 1, b: { c: 2, d: { e: 3 } } }
Output: { "a": 1, "b.c": 2, "b.d.e": 3 }
Input: { a: [1, 2], b: { c: 3 } }
Output: { "a": [1, 2], "b.c": 3 }
Arrays are leaves, so the array stays under key "a".

Sample tests

Input: flattenObject({"a":1,"b":{"c":2,"d":{"e":3}}})
Output: {"a":1,"b.c":2,"b.d.e":3}
Input: flattenObject({"x":{"y":{"z":1}},"w":2})
Output: {"x.y.z":1,"w":2}

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Treating arrays as nested objects produces keys like `a.0`, which the spec excludes here.
  • Prepending a leading dot when the prefix is empty yields keys like `.a`.

Learning resources

  • MDN: Working with objects
Approach & explanation (try first)

A depth-first walk carries the path built so far. Plain objects are descended into; arrays and primitives are written to the result under their full path. Because the walk follows key insertion order, the output keys come out in a predictable order.

Loading...
⌘/Ctrl + Enter

Run your code to see results.