Description
The dig
fn allows safe access to deeply nested properties in an object
by specifying the path as a
dot-delimited string. If any level of the path resolves to undefined
or null
, it returns the
provided fallback value instead of throwing an error.
Code Byte
export const dig = <T extends object, R = any>(
obj: T,
path: string,
fallback: R = undefined
): R | any => {
return path.split('.').reduce((acc: any, key: string) => {
return acc != null && acc[key] !== undefined
? acc[key]
: fallback;
}, obj);
}
Use cases:
- Config reading: Safely retrieve nested config options.
- Data parsing: Access deep values in API responses without extra checks.
- UI rendering: Show default values when nested data is missing.
- Utility libraries: Core helper for object navigation in generic utilities.
Example usage:
import { dig } from './dig.util';
const data = {
user: {
profile: {
name: 'Alice',
settings: { theme: 'dark' }
}
}
};
console.log(dig(data, 'user.profile.name')); // "Alice"
console.log(dig(data, 'user.profile.age', 30)); // 30 (fallback)
console.log(dig(data, 'user.address.street', 'Unknown street')); // "Unknown street"
console.log(dig(data, 'user.profile.settings.theme')); // "dark"