Search code examples
javascriptvariableseval

Using a variable to name another variable javascript


In the process of making a discord bot using node.js and discord.js, I've come to a point where I want to create a new variable, in this case an object with one property (the string "server" and some string for a value.) To name said new variable, I want to use the server ID of the server I'm referring to here, which is stored in another variable. What is a way I can do this?

So far I've tried eval("var " + serverID + " = {'server': 'test'}"), which gave me a syntax error: invalid/unexpected token on the second plus sign (replacing the object with a string still gave me the same error). Everywhere I've looked hasn't been helpful in explaining what is wrong with the eval function, and I'm confused as to how I would do this another way.

In case the first thing that came to your mind was restructuring how I'm working with variables and the types I'm using, whatever this outputs must let me add more information to this variable, which at least in my mind restricts me to using Objects and adding properties. I also store this variable to a JSON file later in the code which also restricts me to using either Arrays or Objects.


Solution

  • I'm going to guess that the eval fails because your serverID is a number (or a string that represents a number), so the statement would look like var 123 = {'server': 'test'}, which would give a syntax error.

    In any case, a simple alternative would be to create a property on an object instead of a variable. Something like:

    var myVariables = {};
    //...
    myVariables[serverID] = {'server': 'test'};
    

    You could even add it to the global object, if it makes sense for your situation and you really need a global variable.