safe-dig
Version:
A safe dig function for navigating nested objects and arrays in JavaScript, with an optional prototype method for all objects.
26 lines (23 loc) • 822 B
JavaScript
// The core safeDig function
function safeDig(obj, ...args) {
try {
return args.reduce((acc, key) => {
// If the accumulator is null or not an object/array, return null
if (acc && (typeof acc === 'object' || Array.isArray(acc))) {
return acc[key] !== undefined ? acc[key] : null; // Explicitly return null when key is not found
}
return null; // Return null if acc is not an object or array
}, obj);
} catch (e) {
return null; // Return null in case of an error
}
}
// Optional function to apply safeDig to Object prototype
function addSafeDigPrototype() {
if (!Object.prototype.safeDig) {
Object.prototype.safeDig = function (...args) {
return safeDig(this, ...args);
};
}
}
module.exports = { safeDig, addSafeDigPrototype };