frontend-challenges icon indicating copy to clipboard operation
frontend-challenges copied to clipboard

446 - Get - typescript

Open jsartisan opened this issue 2 months ago • 0 comments

index.ts

/**
 * Retrieves a value from an object via a path.
 */
export function get<T, R = unknown>(
  object: T,
  path: string | Array<string | number>,
  defaultValue?: R,
): R | unknown {
  const keys = Array.isArray(path)
    ? path
    : path.replaceAll("[", ".").replaceAll("]", "").split(".");

  let result: any = object[keys[0] as keyof T];

  for (let i = 1; i < keys.length; i++) {
    const key = keys[i];

    result = result[key];
    
    if (result === undefined) return defaultValue;
  }

  return result;
}

jsartisan avatar Sep 16 '25 16:09 jsartisan