How do I interpolate a variable as a key in a JavaScript object?
Solution 1:
var a = "whatever";
var b = {};
b[a] = 20;
alert(b["whatever"]); // shows 20
Solution 2:
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.
Solution 3:
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'
.