How to transform the value of a variable into the name of an object’s property?

Asked

Viewed 877 times

0

I have this example of code:

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

what I wish 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 property name becomes "a"... how to make the property name be the value of an existing variable?

  • 1

    This code doesn’t make any sense. Demonstrate better what you want for us to see a viable way to solve what you really need.

  • Do you want the value of the variable to be the name of the object attribute ? type that ? https://jsfiddle.net/filadown/whx4tctz/

  • I think he wants something like: b['foo'] = '2';

  • Here’s a good answer: http://answall.com/a/82668/14674

  • Guys, thanks for the help. The doubt was really simple, just use b[a] = '2' =)! I’m taking the rust out of Js little by little here, thank you!!!

2 answers

5


If I understand correctly, you want to create the attribute in the object b which is worth 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>

In this answer there are more details: /a/82668/14674

3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.