17

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
  • 16,067
  • 27
  • 106
  • 154

2 Answers2

38

Use the square bracket notation []

var something = consts[stringKey];
MrCode
  • 61,589
  • 10
  • 82
  • 110
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