This question is pretty old, but since it is the best result on Google for the query "javascript get object from string", I thought I would share the technique for longer object paths using dot notation.
Given the following:
var foo = { 'bar': { 'alpha': 'beta' } };
We can get the value of 'alpha' from the string as follows:
var objPath = "bar.alpha"; var alphaVal = objPath.split('.') .reduce(function (object, property) { return object[property]; }, foo);
If it is global:
window.foo = { 'bar': { 'alpha': 'beta' } };
Just pass window as initialValue to reduce :
var objPath = "foo.bar.alpha"; var alphaVal = objPath.split('.') .reduce(function (object, property) { return object[property]; }, window);
Basically, we can use reduce to intersect objects, passing the original object as initialValue .
MDN article for Array.prototype.reduce
source share