Skip to main content
05

Implement Lodash's get

Easyobjectsstringslodash

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Implement get(object, path, defaultValue), a version of Lodash's _.get. It reads the value at path inside object, and returns defaultValue when there is nothing there, instead of throwing a TypeError.

path is either a string with dots and square brackets, or an array of keys.

js
const user = { name: 'Dana', address: { city: 'Haifa' }, roles: [{ id: 'admin' }] }

get(user, 'address.city') // 'Haifa'
get(user, 'roles[0].id') // 'admin'
get(user, ['roles', '0', 'id']) // 'admin'
get(user, 'address.zip') // undefined
get(user, 'manager.name', 'none') // 'none'

Requirements

  • A string path splits on ., and [0] means the key 0: 'a[0].b' is the same as ['a', '0', 'b'].
  • If any value along the way is null or undefined, stop and return defaultValue.
  • Return defaultValue only when the resolved value is undefined. A resolved null, 0, false or '' is returned as it is.
  • defaultValue is optional, and get returns undefined when it is missing.

Note

Optional chaining (?.) only works when the path is known while writing the code. get takes the path as data.

Approach

Split the work into two steps:

  1. Normalize the path into an array of keys. An array is used as it is. A string has its brackets turned into dots ('a[0].b' becomes 'a.0.b'), is split on ., and loses empty segments (a path that starts with [0] would otherwise produce an empty first key).
  2. Walk the object one key at a time. Before each step, check whether the current value is null or undefined (current == null covers both). If it is, the path is broken: return defaultValue.

At the end, return defaultValue only if the value is undefined, so real values like null or 0 come back untouched.

The common mistakes

  • current[key] || defaultValue replaces 0, false and '' with the default. Compare with undefined instead.
  • Checking only for undefined while walking: null.x throws too.
  • Splitting on . only turns 'a[0]' into the key 'a[0]', which doesn't exist.

Complexity

O(k) time, where k is the length of the path. Normalizing a string path is O(length of the string).

Follow-ups interviewers ask

  • set(object, path, value): walk the same way, creating missing objects (or arrays, when the next key is a number) as you go.
  • Quoted keys: support paths like a['b.c'], where a key contains a dot. This needs a small tokenizer instead of string replacement.
  • Why not eval or new Function: building code from a path string runs arbitrary code if the path comes from user input.

Reference solution

js
/**
 * @param {Object} object
 * @param {string | Array<string | number>} path
 * @param {*} [defaultValue]
 * @returns {*}
 */
export default function get(object, path, defaultValue) {
  const keys = Array.isArray(path)
    ? path
    : path.replaceAll('[', '.').replaceAll(']', '').split('.').filter(Boolean)

  let current = object
  for (const key of keys) {
    if (current == null) return defaultValue
    current = current[key]
  }

  return current === undefined ? defaultValue : current
}
ts
export default function get(
  object: unknown,
  path: string | Array<string | number>,
  defaultValue?: unknown,
): unknown {
  const keys = Array.isArray(path)
    ? path
    : path.replaceAll('[', '.').replaceAll(']', '').split('.').filter(Boolean)

  let current = object
  for (const key of keys) {
    if (current == null) return defaultValue
    current = (current as Record<string | number, unknown>)[key]
  }

  return current === undefined ? defaultValue : current
}