Skip to the solution
MediumDSA7 min read

Implement lodash.get(obj, path, defaultValue)

166 views

The problem

Problem, as an interviewer would state it: "Implement get(obj, path, defaultValue) — safely reading a deeply nested value from an object via a dot-notation (or array-bracket) path string, returning defaultValue if any part of the path is genuinely missing, matching lodash's own well-known _.get behavior."

Examples:

Code
get({a: {b: {c: 42}}}, "a.b.c"); // 42
get({a: 1}, "x.y.z", "fallback"); // "fallback"

Clarifying questions expected:

  • Does the path need to support BOTH dot notation ("a.b.c") AND array-bracket notation ("a[0].b"), or just one format?
  • If the actual value at the path is a genuine FALSY value (like 0, false, or an empty string), should the default still correctly NOT be used?
  • Should the path also be acceptable as a pre-split array of keys, not just a string?

Code / implementation expected: Yes — real, direct proof of correct dot/bracket path access, correct fallback on a genuinely missing path, and — critically — confirmation a genuine falsy value at the path is correctly returned, not confused with "missing."

  • array
  • get
  • lodash-get
  • 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: get() correctly walks dot and bracket-notation paths, falls back to a default on a genuinely missing path, and correctly preserves a real falsy value like 0

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 123 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 lodash.set(obj, path, value) — create nested path

Continue