Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference an object dynamically?

In Javascript, I have an object:

obj = { one: "foo", two: "bar" };

Now, I want do do this

var a = 'two';
if(confirm('Do you want One'))
{
  a = 'one';
}

alert(obj.a);

But of course it doesn't work. What would be the correct way of referencing this object dynamically?

like image 432
Issac Kelly Avatar asked Oct 04 '08 04:10

Issac Kelly


1 Answers

short answer: obj[a]

long answer: obj.field is just a shorthand for obj["field"], for the special case where the key is a constant string without spaces, dots, or other nasty things. in your question, the key wasn't a constant, so simply use the full syntax.

like image 141
Javier Avatar answered Oct 01 '22 09:10

Javier