Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get value with string key in javascript [duplicate]

Tags:

javascript

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?

like image 645
CorayThan Avatar asked Jun 14 '13 19:06

CorayThan


People also ask

How do you get a value from a key JavaScript?

To get an object's key by it's value:Call the Object. keys() method to get an array of the object's keys. Use the find() method to find the key that corresponds to the value. The find method will return the first key that satisfies the condition.

Can JavaScript objects have duplicate keys?

In JavaScript, an object consists of key-value pairs where keys are similar to indexes in an array and are unique. If one tries to add a duplicate key with a different value, then the previous value for that key is overwritten by the new value.

Can JavaScript set have duplicate values?

The Set object lets you store unique values of any type, whether primitive values or object references. you are passing new object not reference so it is allowing to add duplicate.


2 Answers

Use the square bracket notation []

var something = consts[stringKey];
like image 79
MrCode Avatar answered Oct 20 '22 18:10

MrCode


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?

like image 35
Jóni Lourenço Avatar answered Oct 20 '22 19:10

Jóni Lourenço