Skip to content

Instantly share code, notes, and snippets.

@zachstronaut
Created October 5, 2012 04:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save zachstronaut/3838175 to your computer and use it in GitHub Desktop.
Save zachstronaut/3838175 to your computer and use it in GitHub Desktop.
javascript string object property chain to actual property
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
@millermedeiros
Copy link

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:

var lorem = {ipsum : { bar : 123 }};
console.log( get(lorem, 'ipsum.dolor.amet') ); // undefined
console.log(  lorem.ipsum.dolor.amet  ); // throw ReferenceError: dolor is not defined

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment