33

Possible Duplicate:
Javascript use variable as object name

How do I get JS to treat a string as a reference to a previously defined object? Simplified:

var myObject = new MyObject();

var myString = "myObject";

var wantThisToWork = myString.myproperty;
4
  • 1
    If this is what you think you'll need, then don't use variables for storage. Store myObject inside another object used as a global namespace. var my_namespace = {}; my_namespace.myObject = new MyObject(); var myString = "myObject"; var itWorks = my_namespace[myString].myproperty Commented Jun 8, 2012 at 17:28
  • @amnotiam My answer details what your comment is talking about, it's hard to understand it from a comment. Commented Jun 8, 2012 at 18:14
  • I highly recommend this solution: stackoverflow.com/a/6394168/167129 Commented Apr 23, 2014 at 2:24
  • humanwhocodes.com/blog/2013/06/25/… Commented Aug 22, 2018 at 19:51

4 Answers 4

49

If the variable is in the global scope, you can access it as a property of the global object

var a = "hello world";
var varName = "a";
console.log( window[varName] ); // outputs hello world
console.log( this[varName] ); // also works (this === window) in this case

However, if it's a local variable, the only way is to use eval (disclaimer)

function () {
  var a = "hello world";
  var varName = "a";
  console.log( this[varName] ); // won't work
  console.log( eval(varName) ); // Does work
}

Unless you can put your dynamic variables into an object and access it like a property

function () {
  var scope = {
    a: "hello world";
  };
  var varName = "a";
  console.log( scope[varName] ); // works
}
Sign up to request clarification or add additional context in comments.

5 Comments

nice explanation.I am little confused on why we cant use the Function keyword in this case. stackoverflow.com/questions/36078655/…
@techie_28 You can, you just have to be careful with executing arbitrary code, just like eval. It's typically better to avoid it if possible.
Function(onclickB.replace("p,q", "p,q,r")) this is working fine when onclickB is of the form return someFunc(2,'abc') but when I extract only the function name i.e. when onclickB = 'someFunc',passing it to Function(onclickB).call(....) does not call the function & gives an error..am I doing something stupid here?
@techie_28 That's a separate question, you should create a new post so it's more useful to others... and link it here
8

You can use the eval function.

eval(myString).myproperty

Careful with eval, though, if this is something the user is inputting, it will execute any javascript code!

2 Comments

There are better ways (that others mentioned), don't use eval if you don't have to
Yeah, I know eval shouldn't be used unless absolutely necessary and I just saw those. Did not know about that! +1 to those answers.
7

The only way, as it seems to me, would be to use eval. But as they say, eval is evil - but not in controlled environments. This is the way it is possible, but i don't recommend using eval, unless it is absolutely necessary.

var myObject = new MyObject();
var myString = "myObject";
var wantThisToWork = eval(myString).myproperty;

7 Comments

and why was that downvote for? don't tell me because of eval. I already mentioned that i don't recommend it unless absolutely necessary.
I don't think this deserves a downvote. There are cases when you have to use eval (If you're trying to access a local variable).
exactly! And by this expression I don't mean that the situation of OP (wonder what's the full-form of OP) is one where this is needed. But besides my repeating it multiple times that don't use eval unnecessarily, what is that downvote for?
But it's still not a good answer. I think my answer covers all the cases
i didn't say it was a great answer. all i said is that it wasn't an answer which deserved a downvote.
|
4

Use eval()

var myObject = {};
myObject.myproperty = "Hello";
var myString = "myObject";

var wantThisToWork = eval(myString).myproperty;

7 Comments

weren't multiple eval answers enough? This is exactly what i gave.
Don't repost existing answers, there were already 3 answers like yours when you added it. Added no value to the post.
@ParthThakkar : While, I was writing my answer and the time I posted it, already a hell many answers were posted. Some how notification for already posted answer did not come(slow internet). What made you think that I am interested in what you wrote ?
i didn't say that you were interested in what i wrote. I just said that that was exactly what i gave. Btw, aren't we all fighting over this small question for no reason. I mean, my answer is littered with my whines of someone downvoting it in spite of me warning about the answer....let's just leave this matter. It's being stretched unnecessarily.
@JuanMendes : Every answer has been answered in 10 mins frame. This is how much time you would take, if you are dividing your time between watching football match and typing answer. Already posted message did not appear for me, so had no idea, that already answers were posted.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.