Root object / array / primitive to read from.
Ordered list of keys / indexes to traverse.
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,
);
}
Resolves a value out of a nested object/array using a key path.
Traversal is forgiving: if any segment is
nullorundefined(or the parent isn't indexable), resolution short-circuits and returns the same nullish value rather than throwing. An empty path returnsobjas-is. Paths can mix string and numeric segments — numeric segments index arrays via the same bracket access as object keys.