0

Let's say i want to create an object that is named using a variable? how would i do this? is it even possible?

var aName = "obusdiofu";

aName = {check: true, person: false};

console.log(obusdiofu); //gives me the newly created object?
user5640752
  • 101
  • 1
  • 2
  • 13
  • 3
    It is not possible to construct variable names dynamically without using `eval()`, and you probably shouldn't do that without good reason. You *can* construct object property names dynamically. – Pointy Mar 12 '18 at 19:53
  • **cough** `eval()` **cough** – Ates Goral Mar 12 '18 at 19:55
  • Possible duplicate of [JavaScript set object key by variable](https://stackoverflow.com/questions/11508463/javascript-set-object-key-by-variable) – Ronnie Royston Mar 12 '18 at 20:05

3 Answers3

0

You can't do that directly. You'd want to create an object first, then you can store things as custom properties of that object.

var names = {}
var aName = 'obusdiofu'
names[aName] = { check: true, person: false }
takendarkk
  • 3,347
  • 8
  • 25
  • 37
jmcgriz
  • 2,819
  • 1
  • 9
  • 11
0

Unfortunately, there is no such thing in Javascript, however , you could do something like this :

var aName = "obusdiofu";

this[aName] = {check: true, person: false};

console.log(obusdiofu);

// Or if the code is outside the global scope, then
// you should access it like so :
console.log(this.obusdiofu);

Note: You should be careful though when assigning the aName variable, because not all characters are accepted .

CryptoBird
  • 508
  • 1
  • 5
  • 22
0

Disclaimer first, per MDN:

Do not ever use eval!

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.

That being said, you can achieve something along those lines like this:

let aName = 'obusdiofu';
eval(`var ${aName} = {check: true, person: false}`);
console.log(obusdiofu);

I can't see why that would ever be necessary, and due to the issues with eval() you would be better off doing something like one of the other posted answers.

Herohtar
  • 5,347
  • 4
  • 31
  • 41