Get object by name as string without eval
Solution 1
If variables are global then:
myobject = {"foo" : "bar"};
myname = "myobject";
window[myname].foo
For local:
(function(){
myobject = {"foo" : "bar"};
myname = "myobject";
alert( this[myname].foo );
})();
Solution 2
Local Variable Solution:
You could make all objects that you want to access with a string properties of another object. For example:
var objectHolder = {
myobject: {"foo" : "bar"},
myobject2: {"foo" : "bar"},
myobject3: {"foo" : "bar"}
};
And then access your desired object like this:
var desiredObject = objectHolder["myobject"];
Global Variable Solution:
You can access global variables using a string like this:
window["myobject"];
Solution 3
This question is pretty old, but since it's the top result on Google for the query "javascript get object from string", I thought I'd share a technique for longer object paths using dot notation.
Given the following:
var foo = { 'bar': { 'alpha': 'beta' } };
We can get the value of 'alpha' from a string like this:
var objPath = "bar.alpha";
var alphaVal = objPath.split('.')
.reduce(function (object, property) {
return object[property];
}, foo);
// alphaVal === "beta"
If it's global:
window.foo = { 'bar': { 'alpha': 'beta' } };
Just pass window
as the initialValue
for reduce
:
var objPath = "foo.bar.alpha";
var alphaVal = objPath.split('.')
.reduce(function (object, property) {
return object[property];
}, window);
// alphaVal === "beta"
Basically we can use reduce
to traverse object members by passing in the initial object as the initialValue
.
MDN article for Array.prototype.reduce
Solution 4
since window is a global namespace, you could simply use
window[myname]
Jeroen Ooms
#rstats developer and staff RSE for @ropensci at UC Berkeley.
Updated on November 25, 2020Comments
-
Jeroen Ooms over 3 years
The code below does what I want, but I would like to avoid
eval
. Is there a function in Javascript that looks up an object by its name as defined by in a string?myobject = {"foo" : "bar"} myname = "myobject"; eval(myname);
Some context: I am using this for an application in which a large number of nodes in the dom has a html5
data-object
attribute, which is used in the handler function to connect back to the model.Edit: myobject is neither global nor local, it is defined in one of the parent frames of the handler.
-
thecodeparadox over 11 years@ŠimeVidas I know Sir, just for OP's case. Thanks
-
darksky over 11 yearsYou probably forgot to replace the equal signs with colons in the first part of your post.
-
Loilo over 8 yearsYour second example is a kind of misleading. It's basically the same as the first one - you define
myobject
withoutvar
(means: globally) and then access it bywindow[myname]
(becausethis === window
, in your case). As soon as your context (yourthis
) changes, your example won't work anymore. Long story short: That's not a way to access local variables by name.