Back to Functions

get

object

Gets the value at path of object.

Installation

Import
import { get } from '@tulx/utils';

Source Code

Implementation
/**
 * Gets the value at path of object.
 *
 * @param object - The object to query.
 * @param path - The path of the property to get.
 * @param defaultValue - The value returned for resolved undefined values.
 * @returns Returns the resolved value.
 *
 * @example
 * ```ts
 * const object = { 'a': [{ 'b': { 'c': 3 } }] };
 * get(object, 'a[0].b.c'); // 3
 * get(object, ['a', '0', 'b', 'c']); // 3
 * get(object, 'a.b.c', 'default'); // 'default'
 * ```
 */
export function get<T = unknown>(
  object: Record<string, unknown>,
  path: string | readonly (string | number)[],
  defaultValue?: T
): T | undefined {
  const pathArray = Array.isArray(path) ? path : parsePath(String(path));
  let current: unknown = object;

  for (const key of pathArray) {
    if (
      current === null ||
      current === undefined ||
      typeof current !== 'object'
    ) {
      return defaultValue;
    }
    current = (current as Record<string, unknown>)[String(key)];
  }

  return (current === undefined ? defaultValue : current) as T | undefined;
}

function parsePath(path: string): string[] {
  const keys: string[] = [];
  let current = '';
  let inBrackets = false;

  for (let i = 0; i < path.length; i++) {
    const char = path[i];
    if (char === '[') {
      if (current) {
        keys.push(current);
        current = '';
      }
      inBrackets = true;
    } else if (char === ']') {
      if (current) {
        keys.push(current);
        current = '';
      }
      inBrackets = false;
    } else if (char === '.' && !inBrackets) {
      if (current) {
        keys.push(current);
        current = '';
      }
    } else {
      current += char;
    }
  }

  if (current) {
    keys.push(current);
  }

  return keys;
}

Example

import { get } from '@tulx/utils';

const object = { 'a': [{ 'b': { 'c': 3 } }] };
get(object, 'a[0].b.c'); // 3
get(object, ['a', '0', 'b', 'c']); // 3
get(object, 'a.b.c', 'default'); // 'default'

Related Functions