obj.prop(path)

// ⭐ mixin for objects
const ObjectTools = {
    
    // obj.prop(path)
    prop(path) {
        
        let value = this;
        let components = path.split('.');
        
        while (components.length) {
            
            // pull first component
            let component = components.shift();
            // check if last character === '?'
            const isValueOptional = component.slice(-1) === '?';

            if (isValueOptional) {
                // remove "?"
                component = component.slice(0, -1);
                // get nested property
                value = value[component];
                // return early if value is nullish
                if (value === null || value === undefined) return undefined;
            } else {
                // if not optional, get property directly
                value = value[component];
            }
            
        }
        
        return value;
    }
};

// for node.js module
module.exports = objectTools;

💈範例:

Last updated

Was this helpful?