codetrix
Version:
A lightweight lodash-style utility library
17 lines (16 loc) • 625 B
JavaScript
/**
* Safely retrieves a nested value from an object using a path.
*
* @param obj - The object to query.
* @param path - The path to the nested property (dot-separated).
* @param fallback - The fallback value if the path doesn't exist.
* @returns The value at the nested path or the fallback.
*
* @example
* getNested({ a: { b: 2 } }, 'a.b'); // 2
* getNested({ a: { b: 2 } }, 'a.c', 0); // 0
*/
export function getNested(obj, path, fallback) {
var _a;
return (_a = path.split('.').reduce((acc, key) => acc === null || acc === void 0 ? void 0 : acc[key], obj)) !== null && _a !== void 0 ? _a : fallback;
}