21

I can't figure out how to get an object property using a string representation of that property's name in javascript. For example, in the following script:

consts = {'key' : 'value'}

var stringKey = 'key';

alert(consts.???);

How would I use stringKey to get the value value to show in the alert?

CorayThan
  • 17,174
  • 28
  • 113
  • 161

2 Answers2

42

Use the square bracket notation []

var something = consts[stringKey];
MrCode
  • 63,975
  • 10
  • 90
  • 112
5

Javascript objects are like simple HashMaps:

var consts = {};

consts['key'] = "value";
if('key' in consts) {      // true
   alert(consts['key']);   // >> value
}

See: How is a JavaScript hash map implemented?

Community
  • 1
  • 1