Accessing deep properties and methods of an object with using a path Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?How to Optimize Merge of Two Objects That Include Arrays of ObjectsLightweight CookiemanagerOpen source angularjs pouchdb model persistence layer - release ready?Parsing function is 50 lines longSearching for songs on an Android applicationHashMap and HashSet classes for ES6Interactive small townmodifying globals, “window”, “global” and other objects, in a restorable wayFiltering on an array of object literal properties and their nested array valuesSimplify SVG creation and manipulation using Proxy

What is a more techy Technical Writer job title that isn't cutesy or confusing?

Short story about astronauts fertilizing soil with their own bodies

Does the transliteration of 'Dravidian' exist in Hindu scripture? Does 'Dravida' refer to a Geographical area or an ethnic group?

What did Turing mean when saying that "machines cannot give rise to surprises" is due to a fallacy?

In musical terms, what properties are varied by the human voice to produce different words / syllables?

French equivalents of おしゃれは足元から (Every good outfit starts with the shoes)

How do Java 8 default methods hеlp with lambdas?

What does 丫 mean? 丫是什么意思?

Weaponising the Grasp-at-a-Distance spell

Any stored/leased 737s that could substitute for grounded MAXs?

malloc in main() or malloc in another function: allocating memory for a struct and its members

Why do C and C++ allow the expression (int) + 4*5;

One-one communication

Why complex landing gears are used instead of simple, reliable and light weight muscle wire or shape memory alloys?

newbie Q : How to read an output file in one command line

Does the main washing effect of soap come from foam?

What is "Lambda" in Heston's original paper on stochastic volatility models?

How to make an animal which can only breed for a certain number of generations?

Where and when has Thucydides been studied?

How to resize main filesystem

Is the time—manner—place ordering of adverbials an oversimplification?

Statistical analysis applied to methods coming out of Machine Learning

2018 MacBook Pro won't let me install macOS High Sierra 10.13 from USB installer

What criticisms of Wittgenstein's philosophy of language have been offered?



Accessing deep properties and methods of an object with using a path



Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?How to Optimize Merge of Two Objects That Include Arrays of ObjectsLightweight CookiemanagerOpen source angularjs pouchdb model persistence layer - release ready?Parsing function is 50 lines longSearching for songs on an Android applicationHashMap and HashSet classes for ES6Interactive small townmodifying globals, “window”, “global” and other objects, in a restorable wayFiltering on an array of object literal properties and their nested array valuesSimplify SVG creation and manipulation using Proxy



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1












$begingroup$


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"));









share|improve this question











$endgroup$




bumped to the homepage by Community 14 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • $begingroup$
    Perhaps this would do? return path.split('.').reduce((a, k) => a !== undefined && (typeof a === 'function' ? a()[k] : a[k]), obj)
    $endgroup$
    – elclanrs
    Dec 27 '17 at 17:02











  • $begingroup$
    I ran some tests on jsperf my code is slightly faster, which is suprising
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 17:24










  • $begingroup$
    A for loop is likely to be faster than reduce. Although, "faster" at this level of optimization often doesn't matter. I'd go with what you think reads better.
    $endgroup$
    – elclanrs
    Dec 27 '17 at 17:37






  • 2




    $begingroup$
    Typo in your question. The example calls 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 eg prop = curProp[paths[i]].call ? curProp[paths[i]]() : curProp[paths[i]]; but the improvements are tiny at best.
    $endgroup$
    – Blindman67
    Dec 27 '17 at 17:50










  • $begingroup$
    @elclanrs the question is can my code be optimized. And I get the impression the answer is no. I have ran a js perf test of a solution using reduce and my code is slightly faster. I'm not looking for tiny improvements I'm merely asking is their a faster, more concise way of doing it, since the code was written, 5 years ago.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 17:51

















1












$begingroup$


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"));









share|improve this question











$endgroup$




bumped to the homepage by Community 14 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • $begingroup$
    Perhaps this would do? return path.split('.').reduce((a, k) => a !== undefined && (typeof a === 'function' ? a()[k] : a[k]), obj)
    $endgroup$
    – elclanrs
    Dec 27 '17 at 17:02











  • $begingroup$
    I ran some tests on jsperf my code is slightly faster, which is suprising
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 17:24










  • $begingroup$
    A for loop is likely to be faster than reduce. Although, "faster" at this level of optimization often doesn't matter. I'd go with what you think reads better.
    $endgroup$
    – elclanrs
    Dec 27 '17 at 17:37






  • 2




    $begingroup$
    Typo in your question. The example calls 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 eg prop = curProp[paths[i]].call ? curProp[paths[i]]() : curProp[paths[i]]; but the improvements are tiny at best.
    $endgroup$
    – Blindman67
    Dec 27 '17 at 17:50










  • $begingroup$
    @elclanrs the question is can my code be optimized. And I get the impression the answer is no. I have ran a js perf test of a solution using reduce and my code is slightly faster. I'm not looking for tiny improvements I'm merely asking is their a faster, more concise way of doing it, since the code was written, 5 years ago.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 17:51













1












1








1





$begingroup$


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"));









share|improve this question











$endgroup$




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"));






javascript performance






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 26 '18 at 19:14









200_success

131k17157422




131k17157422










asked Dec 27 '17 at 16:53









MartinWebbMartinWebb

1062




1062





bumped to the homepage by Community 14 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 14 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.













  • $begingroup$
    Perhaps this would do? return path.split('.').reduce((a, k) => a !== undefined && (typeof a === 'function' ? a()[k] : a[k]), obj)
    $endgroup$
    – elclanrs
    Dec 27 '17 at 17:02











  • $begingroup$
    I ran some tests on jsperf my code is slightly faster, which is suprising
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 17:24










  • $begingroup$
    A for loop is likely to be faster than reduce. Although, "faster" at this level of optimization often doesn't matter. I'd go with what you think reads better.
    $endgroup$
    – elclanrs
    Dec 27 '17 at 17:37






  • 2




    $begingroup$
    Typo in your question. The example calls 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 eg prop = curProp[paths[i]].call ? curProp[paths[i]]() : curProp[paths[i]]; but the improvements are tiny at best.
    $endgroup$
    – Blindman67
    Dec 27 '17 at 17:50










  • $begingroup$
    @elclanrs the question is can my code be optimized. And I get the impression the answer is no. I have ran a js perf test of a solution using reduce and my code is slightly faster. I'm not looking for tiny improvements I'm merely asking is their a faster, more concise way of doing it, since the code was written, 5 years ago.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 17:51
















  • $begingroup$
    Perhaps this would do? return path.split('.').reduce((a, k) => a !== undefined && (typeof a === 'function' ? a()[k] : a[k]), obj)
    $endgroup$
    – elclanrs
    Dec 27 '17 at 17:02











  • $begingroup$
    I ran some tests on jsperf my code is slightly faster, which is suprising
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 17:24










  • $begingroup$
    A for loop is likely to be faster than reduce. Although, "faster" at this level of optimization often doesn't matter. I'd go with what you think reads better.
    $endgroup$
    – elclanrs
    Dec 27 '17 at 17:37






  • 2




    $begingroup$
    Typo in your question. The example calls 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 eg prop = curProp[paths[i]].call ? curProp[paths[i]]() : curProp[paths[i]]; but the improvements are tiny at best.
    $endgroup$
    – Blindman67
    Dec 27 '17 at 17:50










  • $begingroup$
    @elclanrs the question is can my code be optimized. And I get the impression the answer is no. I have ran a js perf test of a solution using reduce and my code is slightly faster. I'm not looking for tiny improvements I'm merely asking is their a faster, more concise way of doing it, since the code was written, 5 years ago.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 17:51















$begingroup$
Perhaps this would do? return path.split('.').reduce((a, k) => a !== undefined && (typeof a === 'function' ? a()[k] : a[k]), obj)
$endgroup$
– elclanrs
Dec 27 '17 at 17:02





$begingroup$
Perhaps this would do? return path.split('.').reduce((a, k) => a !== undefined && (typeof a === 'function' ? a()[k] : a[k]), obj)
$endgroup$
– elclanrs
Dec 27 '17 at 17:02













$begingroup$
I ran some tests on jsperf my code is slightly faster, which is suprising
$endgroup$
– MartinWebb
Dec 27 '17 at 17:24




$begingroup$
I ran some tests on jsperf my code is slightly faster, which is suprising
$endgroup$
– MartinWebb
Dec 27 '17 at 17:24












$begingroup$
A for loop is likely to be faster than reduce. Although, "faster" at this level of optimization often doesn't matter. I'd go with what you think reads better.
$endgroup$
– elclanrs
Dec 27 '17 at 17:37




$begingroup$
A for loop is likely to be faster than reduce. Although, "faster" at this level of optimization often doesn't matter. I'd go with what you think reads better.
$endgroup$
– elclanrs
Dec 27 '17 at 17:37




2




2




$begingroup$
Typo in your question. The example calls 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 eg prop = curProp[paths[i]].call ? curProp[paths[i]]() : curProp[paths[i]]; but the improvements are tiny at best.
$endgroup$
– Blindman67
Dec 27 '17 at 17:50




$begingroup$
Typo in your question. The example calls 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 eg prop = curProp[paths[i]].call ? curProp[paths[i]]() : curProp[paths[i]]; but the improvements are tiny at best.
$endgroup$
– Blindman67
Dec 27 '17 at 17:50












$begingroup$
@elclanrs the question is can my code be optimized. And I get the impression the answer is no. I have ran a js perf test of a solution using reduce and my code is slightly faster. I'm not looking for tiny improvements I'm merely asking is their a faster, more concise way of doing it, since the code was written, 5 years ago.
$endgroup$
– MartinWebb
Dec 27 '17 at 17:51




$begingroup$
@elclanrs the question is can my code be optimized. And I get the impression the answer is no. I have ran a js perf test of a solution using reduce and my code is slightly faster. I'm not looking for tiny improvements I'm merely asking is their a faster, more concise way of doing it, since the code was written, 5 years ago.
$endgroup$
– MartinWebb
Dec 27 '17 at 17:51










1 Answer
1






active

oldest

votes


















0












$begingroup$

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";
// --> "No property1 is available", isn't right from the humans perspective noramally

obj["property2"] ? obj["property2"] : "No property2 is available";
// --> "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 =>
if (!currentProperty.hasOwnProperty(pathPart)) return undefined;

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

return currentProperty;






share|improve this answer









$endgroup$












  • $begingroup$
    Runs slower, it seems the original code is fast, though maybe not politically correct for design. Thanks for pointing out the errors will look into this, and re-test.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:33











  • $begingroup$
    Not in the title i agree but it is mentioned: "It is used a lot in my application and I need to speed it up"
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:44










  • $begingroup$
    You're right, I missed that part. My bad. Anyway, at least I pointed out the correctness issue which is more important. Reversed my vote...
    $endgroup$
    – Igor Soloydenko
    Dec 27 '17 at 18:49











  • $begingroup$
    Yes and you are right. I have modified the tags so it is clear. Sorry for any misunderstanding and thank you again for correcting this.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:50










  • $begingroup$
    @MartinWebb it runs slower because of the .forEach it's definitely not as performant compared to a for loop.
    $endgroup$
    – Igor Soloydenko
    Dec 27 '17 at 19:00











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f183715%2faccessing-deep-properties-and-methods-of-an-object-with-using-a-path%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0












$begingroup$

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";
// --> "No property1 is available", isn't right from the humans perspective noramally

obj["property2"] ? obj["property2"] : "No property2 is available";
// --> "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 =>
if (!currentProperty.hasOwnProperty(pathPart)) return undefined;

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

return currentProperty;






share|improve this answer









$endgroup$












  • $begingroup$
    Runs slower, it seems the original code is fast, though maybe not politically correct for design. Thanks for pointing out the errors will look into this, and re-test.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:33











  • $begingroup$
    Not in the title i agree but it is mentioned: "It is used a lot in my application and I need to speed it up"
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:44










  • $begingroup$
    You're right, I missed that part. My bad. Anyway, at least I pointed out the correctness issue which is more important. Reversed my vote...
    $endgroup$
    – Igor Soloydenko
    Dec 27 '17 at 18:49











  • $begingroup$
    Yes and you are right. I have modified the tags so it is clear. Sorry for any misunderstanding and thank you again for correcting this.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:50










  • $begingroup$
    @MartinWebb it runs slower because of the .forEach it's definitely not as performant compared to a for loop.
    $endgroup$
    – Igor Soloydenko
    Dec 27 '17 at 19:00















0












$begingroup$

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";
// --> "No property1 is available", isn't right from the humans perspective noramally

obj["property2"] ? obj["property2"] : "No property2 is available";
// --> "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 =>
if (!currentProperty.hasOwnProperty(pathPart)) return undefined;

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

return currentProperty;






share|improve this answer









$endgroup$












  • $begingroup$
    Runs slower, it seems the original code is fast, though maybe not politically correct for design. Thanks for pointing out the errors will look into this, and re-test.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:33











  • $begingroup$
    Not in the title i agree but it is mentioned: "It is used a lot in my application and I need to speed it up"
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:44










  • $begingroup$
    You're right, I missed that part. My bad. Anyway, at least I pointed out the correctness issue which is more important. Reversed my vote...
    $endgroup$
    – Igor Soloydenko
    Dec 27 '17 at 18:49











  • $begingroup$
    Yes and you are right. I have modified the tags so it is clear. Sorry for any misunderstanding and thank you again for correcting this.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:50










  • $begingroup$
    @MartinWebb it runs slower because of the .forEach it's definitely not as performant compared to a for loop.
    $endgroup$
    – Igor Soloydenko
    Dec 27 '17 at 19:00













0












0








0





$begingroup$

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";
// --> "No property1 is available", isn't right from the humans perspective noramally

obj["property2"] ? obj["property2"] : "No property2 is available";
// --> "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 =>
if (!currentProperty.hasOwnProperty(pathPart)) return undefined;

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

return currentProperty;






share|improve this answer









$endgroup$



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";
// --> "No property1 is available", isn't right from the humans perspective noramally

obj["property2"] ? obj["property2"] : "No property2 is available";
// --> "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 =>
if (!currentProperty.hasOwnProperty(pathPart)) return undefined;

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

return currentProperty;







share|improve this answer












share|improve this answer



share|improve this answer










answered Dec 27 '17 at 18:08









Igor SoloydenkoIgor Soloydenko

2,8231129




2,8231129











  • $begingroup$
    Runs slower, it seems the original code is fast, though maybe not politically correct for design. Thanks for pointing out the errors will look into this, and re-test.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:33











  • $begingroup$
    Not in the title i agree but it is mentioned: "It is used a lot in my application and I need to speed it up"
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:44










  • $begingroup$
    You're right, I missed that part. My bad. Anyway, at least I pointed out the correctness issue which is more important. Reversed my vote...
    $endgroup$
    – Igor Soloydenko
    Dec 27 '17 at 18:49











  • $begingroup$
    Yes and you are right. I have modified the tags so it is clear. Sorry for any misunderstanding and thank you again for correcting this.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:50










  • $begingroup$
    @MartinWebb it runs slower because of the .forEach it's definitely not as performant compared to a for loop.
    $endgroup$
    – Igor Soloydenko
    Dec 27 '17 at 19:00
















  • $begingroup$
    Runs slower, it seems the original code is fast, though maybe not politically correct for design. Thanks for pointing out the errors will look into this, and re-test.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:33











  • $begingroup$
    Not in the title i agree but it is mentioned: "It is used a lot in my application and I need to speed it up"
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:44










  • $begingroup$
    You're right, I missed that part. My bad. Anyway, at least I pointed out the correctness issue which is more important. Reversed my vote...
    $endgroup$
    – Igor Soloydenko
    Dec 27 '17 at 18:49











  • $begingroup$
    Yes and you are right. I have modified the tags so it is clear. Sorry for any misunderstanding and thank you again for correcting this.
    $endgroup$
    – MartinWebb
    Dec 27 '17 at 18:50










  • $begingroup$
    @MartinWebb it runs slower because of the .forEach it's definitely not as performant compared to a for loop.
    $endgroup$
    – Igor Soloydenko
    Dec 27 '17 at 19:00















$begingroup$
Runs slower, it seems the original code is fast, though maybe not politically correct for design. Thanks for pointing out the errors will look into this, and re-test.
$endgroup$
– MartinWebb
Dec 27 '17 at 18:33





$begingroup$
Runs slower, it seems the original code is fast, though maybe not politically correct for design. Thanks for pointing out the errors will look into this, and re-test.
$endgroup$
– MartinWebb
Dec 27 '17 at 18:33













$begingroup$
Not in the title i agree but it is mentioned: "It is used a lot in my application and I need to speed it up"
$endgroup$
– MartinWebb
Dec 27 '17 at 18:44




$begingroup$
Not in the title i agree but it is mentioned: "It is used a lot in my application and I need to speed it up"
$endgroup$
– MartinWebb
Dec 27 '17 at 18:44












$begingroup$
You're right, I missed that part. My bad. Anyway, at least I pointed out the correctness issue which is more important. Reversed my vote...
$endgroup$
– Igor Soloydenko
Dec 27 '17 at 18:49





$begingroup$
You're right, I missed that part. My bad. Anyway, at least I pointed out the correctness issue which is more important. Reversed my vote...
$endgroup$
– Igor Soloydenko
Dec 27 '17 at 18:49













$begingroup$
Yes and you are right. I have modified the tags so it is clear. Sorry for any misunderstanding and thank you again for correcting this.
$endgroup$
– MartinWebb
Dec 27 '17 at 18:50




$begingroup$
Yes and you are right. I have modified the tags so it is clear. Sorry for any misunderstanding and thank you again for correcting this.
$endgroup$
– MartinWebb
Dec 27 '17 at 18:50












$begingroup$
@MartinWebb it runs slower because of the .forEach it's definitely not as performant compared to a for loop.
$endgroup$
– Igor Soloydenko
Dec 27 '17 at 19:00




$begingroup$
@MartinWebb it runs slower because of the .forEach it's definitely not as performant compared to a for loop.
$endgroup$
– Igor Soloydenko
Dec 27 '17 at 19:00

















draft saved

draft discarded
















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f183715%2faccessing-deep-properties-and-methods-of-an-object-with-using-a-path%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar