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;
$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"));
javascript performance
$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.
|
show 4 more comments
$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"));
javascript performance
$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$
Afor
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$
– elclanrs
Dec 27 '17 at 17:37
2
$begingroup$
Typo in your question. The example callsget("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$
– 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
|
show 4 more comments
$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"));
javascript performance
$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
javascript performance
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$
Afor
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$
– elclanrs
Dec 27 '17 at 17:37
2
$begingroup$
Typo in your question. The example callsget("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$
– 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
|
show 4 more comments
$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$
Afor
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$
– elclanrs
Dec 27 '17 at 17:37
2
$begingroup$
Typo in your question. The example callsget("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$
– 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
|
show 4 more comments
1 Answer
1
active
oldest
votes
$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;
$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 afor
loop.
$endgroup$
– Igor Soloydenko
Dec 27 '17 at 19:00
|
show 1 more comment
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
$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;
$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 afor
loop.
$endgroup$
– Igor Soloydenko
Dec 27 '17 at 19:00
|
show 1 more comment
$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;
$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 afor
loop.
$endgroup$
– Igor Soloydenko
Dec 27 '17 at 19:00
|
show 1 more comment
$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;
$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;
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 afor
loop.
$endgroup$
– Igor Soloydenko
Dec 27 '17 at 19:00
|
show 1 more comment
$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 afor
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
|
show 1 more comment
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
$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 thanreduce
. 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 egprop = 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