How can I use the value of the variable a
as a key to lookup a property? I want to be able to say: b["whatever"]
and have this return 20:
var a = "whatever"; var b = {a : 20}; // Want this to assign b.whatever alert(b["whatever"]); // so that this shows 20, not `undefined`
I am asking if it's possible during the creation of b
, to have it contain "whatever":20
instead of a:20
where "whatever" is itself in a variable. Maybe an eval
could be used?
Use Variable as Key for Objects in JavaScript log(obj. key); console. log(obj["key"]); The variable varr was set as the key for the object obj .
To get value in an object's key using a variable referencing that key with JavaScript, we can use square brackets. console. log(obj[name]); to get the name property of the obj object with obj[name] .
Each key in your JavaScript object must be a string, symbol, or number.
var a = "whatever"; var b = {}; b[a] = 20; alert(b["whatever"]); // shows 20
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With