Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - access object member when identifier string is stored in a var

Tags:

javascript

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

like image 785
joshs Avatar asked Feb 27 '10 23:02

joshs


People also ask

How do you use a variable to access the object property?

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.

What are the different ways to access object properties in JavaScript?

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.


1 Answers

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.

like image 136
Rex M Avatar answered Sep 28 '22 17:09

Rex M