Read a Value by Path

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Write get(obj, path, defaultValue) to read a nested value without crashing on missing steps. path is either a string with dots between keys and array indexes in square brackets, such as user.orders[0].total, or an array of keys, such as ["user", "orders", 0, "total"], whose keys are used as they are, dots and all. Walk the path from obj and return the value at the end. If a step along the way is null or undefined, or the value at the end is undefined, return defaultValue (undefined when it isn't given). A value that is there but is null, 0, false or an empty string is returned as it is.

Your code must pass

  • Reads nested keys from a dotted path
  • Reads array indexes in square brackets
  • Accepts the path as an array of keys
  • Returns the default when the path is missing
  • Keeps null and falsy values that are there