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<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"));
return path.split('.').reduce((a, k) => a !== undefined && (typeof a === 'function' ? a()[k] : a[k]), obj)
\$\endgroup\$for
loop is likely to be faster thanreduce
. Although, "faster" at this level of optimization often doesn't matter. I'd go with what you think reads better. \$\endgroup\$get("contact.name",obj)
have the arguments in the wrong order. You can not speed the function up unless you use some very hacky methods. Eg flatten the loop so it runs iterations inline, and use a unique function property to determine the function as typeof is slower egprop = curProp[paths[i]].call ? curProp[paths[i]]() : curProp[paths[i]];
but the improvements are tiny at best. \$\endgroup\$