Skip to the solution
MediumDSA6 min read

Flatten and Unflatten a Nested Object (dot notation & arrays)

971 views

The problem

Problem, as an interviewer would state it: "Create flattenObject(obj) producing { "a.b.0.c": value } from a nested object, and unflattenObject to reverse it. Support arrays and escaping."

Examples:

Code
flattenObject({ a: { b: [{ c: 1 }] } }); // { "a.b.0.c": 1 }
unflattenObject({ "a.b.0.c": 1 });       // { a: { b: [{ c: 1 }] } }

Clarifying questions expected:

  • How should a key that itself contains a dot be represented so it survives the round trip?
  • Should numeric path segments rebuild real arrays on the way back?
  • What about empty objects and arrays, null leaves, and untrusted input paths like __proto__.x?

Code / implementation expected: Yes — real, direct proof of a full round trip, of dotted keys, and of the safety guard.

  • object
  • flatten
  • unflatten

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: flatten then unflatten round-trips arrays, nulls, empty containers and a dotted key via escaping, rejects a __proto__ path, and shows the numeric-keys limit

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 94 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement a Promise Queue (TaskQueue) with concurrency

Continue