Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I interpolate a variable as a key in a JavaScript object?

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?

like image 985
Geo Avatar asked Apr 12 '11 20:04

Geo


People also ask

Can I use a variable as a key JavaScript?

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 .

How can you get the value in an object's key using a variable referencing key?

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] .

Can JavaScript objects have numbers as keys?

Each key in your JavaScript object must be a string, symbol, or number.


1 Answers

var a = "whatever"; var b = {}; b[a] = 20; alert(b["whatever"]); // shows 20 
like image 182
mVChr Avatar answered Sep 20 '22 20:09

mVChr