Say I have a nested object structure like:
var o = { a: { b: { c: 1 } } };
and I have a an accessor String like "a.b.c".
What’s the fastest function to return the specified nested value (to any depth [1..n])?
I.e. in this case, getNested(o, 'a.b.c') === 1 and getNested(o, 'a') === {b:{c:1}}.
What’s the best implementation of getNested?
I hate to give an answer without profiling the code myself, but given that
evalis probably slow, andforEachis slower than just running through a for-loop, I would start with:But I would test this against other approaches.
I don’t think that trying to optimize away the array construction on
splitwould be worthwhile, but this is only one thing to try if you are interested in the fastest way.ADDENDUM
Here is a transcript so you can see it in action:
** ADDENDUM 2 **
So embarassing — I forgot the
varin front ofresultbefore. That might speed it up a bit!Other things to try:
nand just do the for-loop test withi < test.length(might be optimized away anyway)substrings andindexOfs/\./instead of a raw string"."