Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

get

Gets a nested value from an object using a dot-separated path.

TypeScript
Copied!
1/**
2 * Gets a nested value from an object using a dot-separated path.
3 *
4 * @param obj - The object to query.
5 * @param path - The dot-separated string path (e.g. "a.b.c").
6 * @param defaultValue - A fallback value if the path does not exist.
7 * @returns The value at the specified path or the default value.
8 */
9export function get(obj: any, path: string, defaultValue?: any): any {
10  if (!path) return defaultValue;
11
12  const keys = path.split('.');
13  let result = obj;
14
15  for (const key of keys) {
16    if (result != null && typeof result === 'object' && key in result) {
17      result = result[key];
18    } else {
19      return defaultValue;
20    }
21  }
22
23  return result;
24}
  • Safe Nested Access

    Retrieves deeply nested values without risking TypeError, providing a more robust alternative to direct property access.

  • Supports Default Fallback

    Returns a custom defaultValue if the path doesn’t exist, avoiding undefined-related bugs.

  • Flexible Dot-Notation Path

    Accepts dynamic paths like "a.b.c" for deep traversal, making it adaptable to dynamic queries.

  • Null-Safe and Type-Agnostic

    Gracefully handles null and non-object intermediate values without crashing.

Tests | Examples

TypeScript
Copied!
1test('get - retrieves a nested value', () => {
2  const obj = { a: { b: { c: 42 } } };
3  expect(get(obj, 'a.b.c')).toBe(42);
4});
5
6test('get - returns default value if path is missing', () => {
7  const obj = { a: { b: 1 } };
8  expect(get(obj, 'a.b.c', 'default')).toBe('default');
9});
10
11test('get - supports root-level keys', () => {
12  const obj = { x: 10 };
13  expect(get(obj, 'x')).toBe(10);
14});
15
16test('get - handles empty path', () => {
17  const obj = { a: 1 };
18  expect(get(obj, '', 'fallback')).toBe('fallback');
19});
20
21test('get - handles undefined object', () => {
22  expect(get(undefined, 'a.b.c', 'default')).toBe('default');
23});
24
25test('get - works with null object', () => {
26  expect(get(null, 'a.b', 'missing')).toBe('missing');
27});

Common Use Cases

  • Accessing Config or API Responses

    Safely retrieve deeply nested data from config files, JSON responses, or user input.

  • Dynamic Form Handling

    Extract values from nested form state or error structures using user-defined paths.

  • Data Transformation Pipelines

    Use within mapping or filtering logic to pull specific fields without manually checking each level.

  • Logging and Debugging

    Extract nested values from complex logs or error payloads for monitoring or troubleshooting.

  • Template and Rendering Engines

    Resolve dynamic binding paths in rendering engines, UI frameworks, or content templates.

Codebase: Utilities -> Objects -> get | Yevhen Klymentiev