18. Implement get(obj, path, default) — Safe Deep Access

medium

lodash.get shows up constantly for reading API responses defensively. The question tests light parsing plus careful traversal.

The idea

Two phases:

  1. Normalise the path to an array of keys. Convert bracket access [0] into dot access, split on ., and drop empty segments.
  2. Walk the keys. The instant you land on null/undefined, stop and return the default — that's what makes it "safe".

Follow-ups

  • "Optional chaining does this — why implement it?" → ?. needs a static path; get takes a dynamic runtime path.
  • "Write set(obj, path, value)?" → walk the same keys, creating missing objects/arrays as you go.
  • "Quoted keys like a["b.c"]?" → a real tokenizer, worth flagging as the harder version.

What to practice

Implement get, then the matching set that creates intermediate containers.

More questions

index.js
function get(obj, path, defaultValue) {
  // path: "a.b[0].c" or ["a", "b", 0, "c"]
}

const data = { a: { b: [{ c: 42 }] } };
console.log(get(data, 'a.b[0].c'));        // 42
console.log(get(data, 'a.b[1].c', 'n/a')); // "n/a"

Tests

Test Code

Enter JavaScript that runs after your solution. It should return a value or a Promise.