Skip to the solution
MediumDSA7 min read

Implement lodash.set(obj, path, value) — create nested path

70 views

The problem

Problem, as an interviewer would state it: "Implement set(obj, path, value) — writing a value at a deeply nested path, automatically CREATING any missing intermediate objects (or arrays, for numeric path segments) along the way, matching lodash's own well-known _.set behavior."

Examples:

Code
set({}, "a.b.c", 42); // {a: {b: {c: 42}}}

Clarifying questions expected:

  • Does this need to CREATE missing intermediate objects, or only update a path that already fully exists?
  • Should a numeric path segment (like "a[0].b") create a real ARRAY at that level, not a plain object with a "0" key?
  • Does this mutate the original object in place, or return a genuinely new one?

Code / implementation expected: Yes — real, direct proof of missing-intermediate-object creation, correct updates to an already-existing deep path, and correct array creation for a numeric path segment.

  • set
  • lodash-set
  • path

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

7 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: set() correctly creates missing intermediate objects, updates existing deep paths, and creates a real array (not a plain object) for a numeric path segment

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 124 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 p-limit — concurrency limiter for async tasks

Continue