Accessing deep properties and methods of an object with using a path I have a code snippet that I have been using and works. It is used a lot in my application and I need to speed it up. Is there a faster better way of deep accessing objects using a string path. It needs to able to access properties and methods, see my examples below:

     function get(obj, path) {
        var paths = path.split('.'),
        curProp = obj;
        for(var i=0;i&lt;paths.length;i++){
            if (!curProp[paths[i]]) return 
            curProp = (typeof curProp[paths[i]] !== "function") ? curProp[paths[i]] : curProp[paths[i]]() ;
        }
        return curProp;
    }


The snippet gets the property via the path for the object passed

var obj = {contact:{name:"john"}};
console.log(get(obj, "contact.name"));


If the object has a method that returns an object it can return that too

var obj = {contact:function(){return {name:"john"}}};
console.log(get(obj, "contact.name"));
If we're talking functional-programming, I'd use .forEach() instead of a for loop. It abstracts the iteration process.



if (!curProp[paths[i]]) return does not seem quite right to me, because it will work funny with falsy values. It's better to rely on object.hasOwnProperty(), or Object.keys() depending on the way you want it to work.

Example:

var obj = {};
obj["property1"] = 0;
obj["property2"] = "";

obj["property1"] ? obj["property1"] : "No property1 is available";
  // --&gt; "No property1 is available", isn't right from the humans perspective noramally

obj["property2"] ? obj["property2"] : "No property2 is available";
  // --&gt; "No property2 is available"




I think, it's always good to spell out the return value. In other words, return undefined is better than return in this function.



Slightly different variant:

function get(targetObject, targetPropertyPath) {
    const pathPartList = targetPropertyPath.split('.');
    let currentProperty = targetObject;

    pathPartList.forEach(pathPart =&gt; {
        if (!currentProperty.hasOwnProperty(pathPart)) return undefined;

        const property = currentProperty[pathPart];
        currentProperty = (typeof property !== 'function') ? property : property();
    });

    return currentProperty;
}