JavaScript and Consts [duplicate] - javascript

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 4 months ago.
const A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
Result:
undefined
undefined
Second try:
var A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
Result:
undefined
undefined
How am I supposed to do this then? And can somebody explain why this doesn't work in JavaScript the way one would expect it to work coming from other languages?

The correct way is:
const A = 0;
const LOOKUP = {};
LOOKUP[A] = 'A';
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);

const LOOKUP = { A : "A"};
The left side of the colon means that the key is the string "A". The string part is implicit, since all keys are strings (or symbols). So to access the property, you need to do console.log(LOOKUP.A) or console.log(LOOKUP["A"])
If you want the key to be a computed value, then you need to use square brackets:
const LOOKUP = { [A]: "A" };
That means that we should resolve the variable A, and use its value as the key. That key is the number 0, which then gets coerced into the string "0". You can then look it up by any of console.log(LOOKUP["0"]), console.log(LOOKUP[0]), or console.log(LOOKUP[A])

Looks like you are searching for some enums (typescript):
enum ETest {
A = 1
};
console.log(ETest['A']); // 1
console.log(ETest[1]); // A

Doing LOOKUP[A] is like doing LOOKUP[0] which is undefined.
You should try it as
console.log(LOOKUP["A"])

This has nothing to do with const or var keyword. The way you are trying to access an object property is incorrect.
const A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP["A"]); // Correct Approach: Property access through bracket notation should be done using a string (or a variable assigned to a string).
console.log(LOOKUP[0]); // Property `0` doesn't exist on object `LOOKUP`, so it'll return `undefined`.

Related

Java-Constants-like Map object in Javascript [duplicate]

This question already has answers here:
JavaScript set object key by variable
(8 answers)
Closed 2 years ago.
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.

Defining an object with a dynamic key in node js (javascript) [duplicate]

This question already has answers here:
How To Set A JS object property name from a variable
(8 answers)
Closed 4 years ago.
I need to do this :
let obj = {}
obj.obj1 = {'obj11':5}
console.log(obj.obj1.obj11)
//5
but I need to define the last key of the last object dynamically for example, something like this:
let obj = {}
key = 'obj11'
obj.obj1 = { key :5}
console.log(obj.obj1.obj11)
// undefined
Try
obj.obj1[key] = 5;
console.log(obj.obj1.obj11);
The object notation syntax does not support variables as keys directly, but java-script dictionaries do.
To evaluate the variable in the object notation syntax, use a bracket like so
obj.obj1 = {[key]: 5};
console.log(obj.obj1.obj11);
To define computed properties in javascript objects use [].
Try the following:
let obj = {}
key = 'obj11'
obj.obj1 = { [key] :5}
console.log(obj.obj1.obj11)
For reference : Reference
You'll have to use bracket notation for this like
let obj = {}
key = 'obj11'
obj.obj1 = { [key] :5}
console.log(obj.obj1.obj11)
Yes, you can do this:
console.log(obj.obj1[key]);
Every object in JavaScript is basically a dictionary so you can access it via the dictionary syntax.

Going through a object with a variable [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 6 years ago.
I guess I didnt really know how to ask this question for me to find an answer.
So I have three variables that are going to make this function do what it has to
function gatherDataForGeographic(ele) {
var $this = $(ele)
var $main_title = $this.find('.options-title'),
$option = $this.find('.option');
var arr = []
var reportAreas = reportManager.getReportAreasObject();
$option.each(function () {
var $this = $(this)
var $checkbox = $this.find('.checkbox');
var type = $this.data('type'),
index = $this.data('index');
if ($checkbox.hasClass('checkbox--checked')) {
console.log(reportAreas.type)
} else {
return true;
}
})
return arr;
}
//this will return an object that I need to index
var reportAreas = reportManager.getReportAreasObject();
//this will get the a key that i need from the object
var type = $this.data('type');
//this will give me the index I need to grab
var index = $this.data('index');
So what I am trying to do is go through the object based on the type(or key) from the option selected by a user
The problem...
It is looking for reportArea.type[index] and is not recognizing it as a variable and I keep getting undefined because .type does not exist.
Is there a way for it to see that type is a variable and not a key?
You can use dynamic properties in JS using the bracket syntax, not the dot syntax:
reportAreas[type]
That will resolve to reportAreas['whateverString'] and is equivalent to reportAreas.whateverString- reportAreas.type however, is a literal check for type property.
reportArea[type][index]
JavaScript objects are just key-value pairs and the dot syntax is just syntactic sugar for the array notation.
object['a']
and
object.a
Are the same thing, basically.

javascript: I need to get an object key from the function argument

vm.contributorAmountPerYear[index-1] gets me an object, and I want its key to be the year argument of the function.
function getAgriAmount(year,amount,index) {
if (typeof amount !== "number" ) {
amount = parseInt(amount ||0);
};
var argiYearlyLocalCost = vm.argiterraYearlyLocalCost;
console.log(vm.contributorAmountPerYear[index-1].year);
}
vm.contributorAmountPerYear[index-1][year]
For any javascript object, you should keep in mind that if you use . dot notation, you cannot access the properties for keys that come from a variable and are determined at runtime. Use square bracket notation [] for such a case. This should work:
vm.contributorAmountPerYear[index-1][year];
Dot notation should be used when you already know the key:
var cuteJavaScriptObject = {
animal : 'cat'
}
var myVar = 'animal';
console.log(cuteJavaScriptObject.animal); // OK
console.log(cuteJavaScriptObject.myVar); // Wrong !!
console.log(cuteJavaScriptObject[myVar]); // Now OK

object Key in javascript class/dictionary?

I have a Javascipt object which I use as dictionary
var obj={
xxx:'1'
yyy:'2'
}
However -
xxx and yyy should be a jQuery object.
something like :
var obj =
{
$('#div1'):'1' ,
$('#div2'):'2'
}
is it possible ?
also, How can I get the "value" for key $('#div2') ?
p.s.
I the $.data cant help me here since its also a key value
and i need in the key - object Type also.
Object keys can only be strings ( or Symbol), period. See Member Operators - Property Names # MDN.
Choose a reasonable string representation, and use that. In this case, I'd say the selector string looks like a decent choice:
{
'#div1': '1',
'#div2': '2'
}
also, How can I get the "value" for key $('#div2') ?
Use one of the member operators, either dot notation
var obj = { /* stuff */ };
var value = obj.propertyName;
console.log(value);
or bracket notation (more useful for property names not known until runtime):
var value = obj['propertyName'];
Use a WeakMap which works like a dictionary where the key can be anything. Note that you cannot list all the keys of the map
const aMap = new WeakMap;
const anObject = {};
aMap.set(Number, "It's the Number class")
aMap.set(anObject, "It's an object")
console.log(aMap.get(Number)) // It's the Number class
console.log(aMap.get(anObject)) // It's an object

Categories