JSFiddle - React, Tailwind, and code Playground

by kentaromiura

JavaScript

function foo (object, path, defaultValue){
    
    if(arguments.length == 2){ // generic pattern
        defaultValue = path;
        path = object;
        object = this;
    }
    
    var result = defaultValue,
        paths = path.split('.'),
        part = '',
        actual = object
    
    while (part = paths.shift()){
        if (typeof(actual) == 'object' && part in actual){
            actual = actual[part]
        } else {
            actual = undefined
            paths = []
        }  
    }
    
    if (actual !== undefined){
        result = actual
    }
    
    return result
}

foo.call({a:{b:"bye"}}, 'a.b', 'xxx', undefined)


alert(foo.call({a:{b:'bye'}}, 'a.b', 'xxx'))