FrontendPro

10Implement get(object, "a.b.c") with a default value

easyAbout 15 minutesCodingobjectsstringslodash

Problem

Implement get(object, path, defaultValue), like Lodash's _.get. It reads a nested value by path and returns defaultValue when the value is missing.

const user = { profile: { emails: ["a@x.com", "b@x.com"], age: 0 } };
get(user, "profile.emails[1]"); // "b@x.com"
get(user, ["profile", "age"]); // 0
get(user, "profile.phone.home", "n/a"); // "n/a"

Requirements

  • path is a dot string, may use [index] for arrays, or is an array of keys.
  • Return defaultValue when the resolved value is undefined, including when a step in the middle is null or undefined.
  • Return real falsy values (0, "", false, null) as they are.
  • Never throw while walking the path.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Step-by-step

An array path is already a list. For a string, rewrite [1] as .1, split on ., and drop empty parts: "a[0].b" becomes ["a", "0", "b"].

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever