Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@millermedeiros millermedeiros commented Oct 5, 2012

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