How to transform the value of a variable into the property name of an object? [duplicate]

0

I have this code sample:

var a = 'foo';
var b = {a:'2'};
b.foo //undefined

What I want is that b.foo exists and returns "2" in this example, but when creating the variable "b" the variable "a" ceases to exist when called inside the object what happens is that the name of the property becomes "a" ... how do I make the property name be the value of an existing variable?

    
asked by anonymous 15.02.2016 / 17:39

2 answers

5

If I understand you, you want to create the attribute on the object b which is in the value of a . So you can do it like this:

var a = 'foo';
var b = {};
b[a] = '2';

document.getElementById('saida').innerHTML = 'b.foo = ' + b.foo;
<p id='saida'></p>

More details on this response: link

    
15.02.2016 / 17:50
2

ES6 introduces computerized property names, which allow you to do:

var a = 'foo';

var b = {[a]: 2};

console.log(b);

Reference: Developer Mozilla - Object initializer

    
15.02.2016 / 17:50