I've got a pretty simple question (and tentative answers), I just want to see if maybe there is a better answer out there.
How can you access an object member in javascript when the member identifier is stored in another variable? Example:
state = 'sync';
messages = {
'sync': 'asdf',
'ready': 'asdf',
'complete': 'asdf'
};
Possibilities:
1. message = eval('messages.' + state);
What other ways are there? Anything cleaner? In php it would be simple $message = $messages->$sync
.
I'm sure this question has been answered many times but it is tough to search for... all I get are eval responses when I search for 'variable variables'
Thanks
Answer: Use the Square Bracket ( [] ) Notationnotation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] . Where the dot notation is easier to read and write, the square bracket notation offers much more flexibility since the value between the brackets can be any variable or expression.
The keys in this array are the names of the object's properties. There are two ways to access properties: dot notation and bracket notation.
var message = messages[state];
Every object in JavaScript is not only an object in the more usual sense, but it is also a dictionary populated by its members.
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