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?
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?
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 }
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 .
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 runeval()
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 whicheval()
was invoked, which can lead to possible attacks in ways to which the similarFunction
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.