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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With