FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Easy

Get

10mins

Implement a function get(obj, path, defaultValue) that safely accesses deeply-nested properties in JavaScript objects.

The function should:

  • Take in an object, a path (string in dot/bracket notation or an array of keys), and an optional default value.
  • Return the value if the path exists, otherwise return the default value.
  • Handle both dot notation (a.b.c) and array indexes (a.b[0].c).

Examples

const obj = { a: { b: { c: 3 } } }; get(obj, 'a.b.c'); // 3 get(obj, 'a.b.d', 'default'); // 'default' get(obj, ['a', 'b', 'c']); // 3 get({ a: { b: [10, 20, { c: 30 }] } }, 'a.b[2].c'); // 30 get(null, 'a.b', 'fallback'); // 'fallback'

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests