80

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
  • 795,719
  • 175
  • 1,089
  • 1,143
Venkat Papana
  • 4,757
  • 13
  • 52
  • 74

3 Answers3

150

You can access objects like arrays:

alert(o[key]);
OverZealous
  • 39,252
  • 15
  • 98
  • 100
13

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
  • 45,213
  • 22
  • 199
  • 169
Lance
  • 1,889
  • 14
  • 12