6

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);

  1. turn message into a hash (in prototype or jquery--not sure about jquery) and access through the framework's method

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

Çağdaş Tekin
  • 16,592
  • 4
  • 49
  • 58
joshs
  • 1,890
  • 1
  • 17
  • 20

1 Answers1

9
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.

Rex M
  • 142,167
  • 33
  • 283
  • 313
  • 1
    Short and sweet and correct. BTW, Josh, this works whether or not your property names in the messages object are enclosed in quotes. – Robusto Feb 27 '10 at 23:46