54

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?

conny
  • 9,973
  • 6
  • 38
  • 47
Geo
  • 93,257
  • 117
  • 344
  • 520
  • possible duplicate of [How to create a dynamic key to be added to a javascript object variable.](http://stackoverflow.com/questions/2462800/how-to-create-a-dynamic-key-to-be-added-to-a-javascript-object-variable) and [pass variable into javascript object](http://stackoverflow.com/questions/3309221/pass-variable-into-javascript-object) and probably others... – Felix Kling Apr 12 '11 at 20:25
  • 1
    I'm guessing when you say "interpolate," you mean "use." Just so it doesn't cause you problems in the future, interpolate means "estimate unknown values between known values" and doesn't fit in this question title at all. – foobarbecue Feb 03 '15 at 15:26
  • 3
    No, he's using correct terminology. You're referring to interpolation in the field of mathematics. https://en.wikipedia.org/wiki/Interpolation He's referring to interpolation in the field of computer science. https://en.wikipedia.org/wiki/String_interpolation. :-) – Aaron Gray Jul 23 '15 at 23:21
  • I think https://stackoverflow.com/questions/6500573/dynamic-keys-for-object-literals-in-javascript asks the same thing but formulated in a different way, neither of them in a particularly _wrong_ way. – conny Apr 17 '18 at 16:22

6 Answers6

59

This works in Firefox 39 and Chrome 44. Don't know about other browsers. Also it doesn't work in nodejs v0.12.7.

var a = "whatever";
var b = { [a]: 20 };
console.log(b["whatever"]); // shows 20

That is, to interpolate a variable, enclose it in brackets.

I'm not sure if this is a part of any standard. Originally, I saw such syntax here: https://hacks.mozilla.org/2015/07/es6-in-depth-classes/ where the author defined:

[functionThatReturnsPropertyName()] (args) { ... }

I'm also not sure if you should use that syntax. It's not widely known. Other members on your team might not understand the code.

mbezjak
  • 591
  • 5
  • 3
  • 3
    Javascript syntax support is more important that just code readability. It matters that the user's browser doesn't fail! The syntax is part of the upcoming ECMAScript 6, and it's only supported in very recent browsers: https://kangax.github.io/compat-table/es6/#object_literal_extensions – Carl Walsh Aug 07 '15 at 15:58
  • 1
    v4.2.6 also supports it – Kostanos Oct 26 '17 at 15:43
  • 1
    Totally the right answer for those who can use ES6, shame some browsers do not yet even in 2018. This solution is better than the accepted answer here as it provides more legible and concise code. – tpartee Jan 30 '18 at 22:40
  • 1
    This is a great answer, because it allows you to construct the object in one statement, which plays nicely with one-line arrow functions with parentheses – Elle Mundy Mar 07 '19 at 16:08
  • This should be safe to use at this point in time unless you're looking to support IE. – Anirudh Ramanathan Aug 03 '21 at 18:49
57
var a = "whatever";
var b = {};
b[a] = 20;
alert(b["whatever"]); // shows 20
mVChr
  • 49,587
  • 11
  • 107
  • 104
  • 3
    Disagree that this is a poor answer on the merit of the code and answering the OP's question. Agree that it could be better by adding some supporting text to explain why what the OP wants to do doesn't simply work in JS and some reasoning behind the answer's operation. Supporting citations would also be a welcome addition. But this is a solid solution pre-ES6. – tpartee Jan 30 '18 at 22:37
6
var a = "whatever";
var b = {a : 20};
b[a] = 37;
alert(b["whatever"]); // 37

'a' is a string with the value 'a'. a is a variable with the value 'whatever'.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
5

Great question. I had a time trying to figure this out with underscore but the answer couldn't be more simple:

var a = "whatever";
var b = {a : 20};

var array = [a, b]
var answer = _.object([[array]])// {whatever: {a:20}}//NOTICE THE DOUBLE SET OF BRACKETS AROUND [[array]]

I hope this helps!

rashadb
  • 2,515
  • 4
  • 32
  • 57
2

Try this:

var a = "whatever";
var c = "something";
var b = {whatever : 20, something: 37};
alert(b[a]); // Shows 20
alert(b[c]); // Shows 37

Here is the fiddle.

Or if I understand from the below comments correctly, try this:

var a = "whatever";
var b = {a : 20};
alert(b.a); // Shows 20
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Naftali
  • 144,921
  • 39
  • 244
  • 303
0

To show all options, I want mention the CoffeeScript way of doing this, which is:

var a = "whatever";
var b = (
  obj = {},
  obj["" + a] = 20,
  obj
);

alert(b.whatever); // 20

Although I prefer:

var a = "whatever";
var b = {};
b[a] = 20;

alert(b.whatever); // 20
Benny Code
  • 51,456
  • 28
  • 233
  • 198