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?

0

2 Answers 2

42

Use the square bracket notation []

var something = consts[stringKey];
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.