Skip to the solution
MediumDSAAsked in 20245 min read

Deep Map Keys

3.5k views

The problem

Problem, as an interviewer would state it: "Implement deepMapKeys(value, fn) — recursively transforming every KEY of nested objects (including objects inside arrays) with fn, leaving values untouched."

Examples:

Code
deepMapKeys({ a: { b: [{ c: 1 }] } }, k => k.toUpperCase());
// { A: { B: [{ C: 1 }] } }

Clarifying questions expected:

  • Should keys inside objects that live inside arrays be mapped too?
  • If two keys map to the same new key, which one wins?
  • Which values count as "objects to descend into" — and what about a Date or a circular reference?

Code / implementation expected: Yes — real, direct proof at every depth, on a collision, and on a circular structure.

  • object
  • recursion

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

5 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: keys are mapped at every depth including inside arrays, and a mapper returning __proto__ shows why defineProperty is the safe write

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 54 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

DOM event delegation target

Continue