views:

193

answers:

5

How do I identify an item in a hash array if the key of the array is only known within a variable? For example:

var key = "myKey";
var array = {myKey: 1, anotherKey: 2};
alert(array.key);

Also, how would I assign a value to that key, having identified it with the variable?

This is, of course, assuming that I must use the variable key to identify which item in the array to alert.

Thanks in advance!

+1  A: 

Use

alert(array[key]);

That is the standard syntax for what you are asking.

Kathy Van Stone
+1  A: 

You can call the key like:

alert(array[key]);
Ben Rowe
+1  A: 

With traditional array notation:

alert(array[key]);
deceze
+1  A: 

Access it just like you would an index in an array. For the example you gave: alert(array[key]);

Chris Doble
+4  A: 

What you have there:-

var array = {myKey: 1, anotherKey: 2};

- is not an Array. It is a native Object object with two properties.

An ECMAScript Array is also an object, though a more specialized object type, having a length property, among other things.

To answer your question, you can use the square bracket property access operators. Renaming your variable to myObj, that would be myObj[ key ], where key is an identifier that resolves to a value that is converted to a string.

For a brief explanation, see: How do I access a property of an object using a string?.

For more detail, see ECMA-262-3 in detail. Chapter 7.2. OOP: ECMAScript implementation

Garrett
+1 Great answer, Dmitry's series are really good...
CMS