Get an object by name as a string without eval

The following code does what I want, but I would like to avoid eval . Is there a function in Javascript that searches for an object by its name, as defined in the string?

 myobject = {"foo" : "bar"} myname = "myobject"; eval(myname); 

In some context: I use this for an application in which a large number of nodes in dom have the html5 data-object attribute, which is used in the handler function to connect to the model.

Edit: myobject is neither global nor local; it is defined in one of the parent frames of the handler.

+6
source share
4 answers

If the variables are global, then:

 myobject = {"foo" : "bar"}; myname = "myobject"; window[myname].foo 

Demo

For local:

 (function(){ myobject = {"foo" : "bar"}; myname = "myobject"; alert( this[myname].foo ); })(); 

Demo

+13
source

Local solution:

You can make all the objects you want to access with the string properties of another object. For instance:

 var objectHolder = { myobject: {"foo" : "bar"}, myobject2: {"foo" : "bar"}, myobject3: {"foo" : "bar"} }; 

And then access your desired object as follows:

 var desiredObject = objectHolder["myobject"]; 

Global variable solution:

You can access global variables using the following line:

 window["myobject"]; 
+11
source

since the window is a global namespace, you can simply use

 window[myname] 
+3
source

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); // alphaVal === "beta" 

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); // alphaVal === "beta" 

Basically, we can use reduce to intersect objects, passing the original object as initialValue .

MDN article for Array.prototype.reduce

0
source

Source: https://habr.com/ru/post/922682/


All Articles