I am trying to get a static Java-like map object working in Javascript. I am not a javascript expert, but am wondering if this is possible. What I am trying to do is the following:
I am defining
const MY_CONST_1 = 'Constant 1 value';
const MY_CONST_2 = 'Constant 2 value';
and a "map-like" object like this:
const CONST_AMOUNT_MAP = {
MY_CONST_1: 30,
MY_CONST_2: 22
}
Then, in a function I define:
function getAmount(constValue) {
return CONST_AMOUNT_MAP[constValue];
}
My expectation would be that the above function when called with
getAmount('Constant 1 value')
returned the number "30". However,
CONST_AMOUNT_MAP[constValue];
returns "undefined". Only
CONST_AMOUNT_MAP[MY_CONST_1]
returns the correct amount.
Is it possible to define an Object such as CONST_AMOUNT_MAP that allows to lookup entries based on pre-defined const variables rather than based on the actual value of the consts?
Thank you
When you define an object literal, the key names are given literally - they're not evaluated. In other words:
const CONST_AMOUNT_MAP = {
MY_CONST_1: 30,
MY_CONST_2: 22
}
...makes an object with a key named MY_CONST_1
, not the value of any variable you've defined with the name MY_CONST_1
.
You can achieve what you're after by instead declaring your keys wrapped in []
, which will force the enclosed to be evaluated.
const CONST_AMOUNT_MAP = {
[MY_CONST_1]: 30,
[MY_CONST_2]: 22
}
Or
const CONST_AMOUNT_MAP = {};
CONST_AMOUNT_MAP[MY_CONST_1] = 30;
CONST_AMOUNT_MAP[MY_CONST_2] = 22;
Note that the keys, however you add them, must be strings or symbols. Since you mention 'map', be aware that there are true maps in JS, in which the keys can be of any data type.