8

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?

Issac Kelly
  • 6,309
  • 6
  • 43
  • 50

3 Answers3

20

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.

Javier
  • 60,510
  • 8
  • 78
  • 126
6

Like this:

obj[a]
yfeldblum
  • 65,165
  • 12
  • 129
  • 169
2

As a side note, global variables are attached to the "window" object, so you can do

var myGlobal = 'hello';
var a = 'myGlobal';
alert(window[a] + ', ' + window.myGlobal + ', ' + myGlobal);

This will alert "hello, hello, hello"

Greg
  • 316,276
  • 54
  • 369
  • 333