71

How to access an object using a variable as key. Here is my code sample:

var o = {"k1": "111", "k2": "222"};
alert(o.k1); //working fine
var key = "k"+1; alert(key); // k1
alert(o.key); //not working
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
Venkat Papana
  • 4,547
  • 13
  • 49
  • 73

3 Answers3

128

You can access objects like arrays:

alert(o[key]);
OverZealous
  • 38,722
  • 15
  • 96
  • 100
10

Change the last line to: alert(o['k1']); or alert(o[key]); where key is your dynamically constructed property key.

Remember you can access object's properties with array notation.

3

Consider using a for...in loop

John Slegers
  • 41,615
  • 22
  • 193
  • 161
Lance
  • 1,881
  • 14
  • 12