← All tasksJavaScript · Middle

get: value by path

Write a function get(obj, path, defaultValue), like lodash's. The path is a string like "a.b[0].c" or an array of keys ["a", "b", 0, "c"].

If you hit null or undefined along the way, or the final value is undefined, return defaultValue. Values 0 and null at the end of the path are real and returned as is.

Tests (7)

  1. const obj = { a: { b: [{ c: 42 }] } };
    expect(get(obj, 'a.b[0].c')).toBe(42);
  2. expect(get({ a: { b: 1 } }, ['a', 'b'])).toBe(1);
  3. expect(get({ list: [10, 20] }, 'list[1]')).toBe(20);
  4. expect(get({ a: null }, 'a.b.c', 'none')).toBe('none');
  5. expect(get({}, 'x.y')).toBe(undefined);
  6. expect(get({ a: { b: 0 } }, 'a.b', 5)).toBe(0);
  7. expect(get({ a: { b: null } }, 'a.b', 5)).toBe(null);