ChemPal Documentation - v0.0.13-beta.5
    Preparing search index...

    Function getPath

    • Resolves a value out of a nested object/array using a key path.

      Traversal is forgiving: if any segment is null or undefined (or the parent isn't indexable), resolution short-circuits and returns the same nullish value rather than throwing. An empty path returns obj as-is. Paths can mix string and numeric segments — numeric segments index arrays via the same bracket access as object keys.

      Parameters

      • obj: unknown

        Root object / array / primitive to read from.

      • path: readonly PropertyKey[]

        Ordered list of keys / indexes to traverse.

      Returns unknown

      The value at the resolved path, or undefined when any segment of the path is missing.

      getPath({ a: { b: { c: 1 } } }, ["a", "b", "c"]); // 1
      getPath({ a: { b: 1 } }, ["a", "x"]); // undefined
      getPath({ items: [10, 20, 30] }, ["items", 1]); // 20
      getPath({ a: null }, ["a", "b"]); // null (short-circuits)
      getPath({ a: 1 }, []); // { a: 1 }
      export function getPath(obj: unknown, path: readonly PropertyKey[]): unknown {
      return path.reduce<unknown>(
      (acc, key) =>
      acc == null ? acc : (acc as Record<PropertyKey, unknown>)[key],
      obj,
      );
      }