SOURCE

const obj = {
    user: {
        profile: {
            name: 'Sunday',
            age: 30,
        }
    }
}

function safeGet(obj, path, defaultValue = undefined) {
    const keys = path.split('.');
    return keys.reduce((acc,key)=>{
        if(acc && acc.hasOwnProperty(key)){
            return acc[key]
        } else {
            return defaultValue
        }
    },obj)
}

console.log(safeGet(obj, 'user.profile.name'));
console.log(safeGet(obj,'user.profile.gender','N/A'))
console 命令行工具 X clear

                    
>
console