Created
October 5, 2012 04:55
-
-
Save zachstronaut/3838175 to your computer and use it in GitHub Desktop.
javascript string object property chain to actual property
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function resolve(obj, path) { | |
var prop; | |
path = path.split('.'); | |
while (obj = obj[path.shift()]) { | |
prop = obj; | |
} | |
return prop; | |
} | |
resolve(window, 'document.body'); // returns value of window.document.body |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have the "same" on amd-utils/object/get - beware that it is slow (ie. shouldn't be called too often) but it can be useful in cases where you might not know if a certain property exists or not:
It would be useful if JS had something similar (more concise and faster) natively. (similar to CoffeeScript existential Operator)
See also: amd-utils/object/set and amd-utils/object/namespace