javascript array with names of variables

50,969

Solution 1

Javascript let's you access object properties dynamically. For example,

var person = {name:"Tahir Akhtar", occupation: "Software Development" };
var p1="name";
var p2="occupation";
console.log(person[p1]); //will print Tahir Akhtar
console.log(person[p2]); //will print Software Development

eval on the other hand lets you evaluate a complete expression stored in a string variable.

For example (continuing from previous example):

var tahir=person;
console.log(eval('person.occupation'));//will print Software Development
console.log(eval('tahir.occupation'));//will print Software Development

In browser environment top level variables get defined on window object so if you want to access top level variables you can do window[myvar]

Solution 2

You can use eval(myArray[i]) to do this. Note that eval() is considered bad practice.

You might consider doing something like this instead:

var myArray = ["name", "age", "genre"];
var i;
for (i = 0; i < myArray.length; i++) {
    console.log(variable[myArray[i]]);
}

Solution 3

You could parse the variable yourself:

var t = myArray[0].split(".");
console.log(this[t[0]][t[1]]);

Solution 4

See this question for how to get hold of the gloabal object and then index into that:

var global = // code from earlier question here
console.log(global[myArray[0]])

Hmm... I see now that your "variable names" contain dots, so they are not actually single names. You'll need to parse them into dot-delimited parts and do the indexing one link at a time.

Share:
50,969
Leth
Author by

Leth

Serious in the morning, funny in the night, with one great objective: challenge the worldview. Main Weapons: - javaScript, jQuery, HTML/CSS, Bootstrap Twitter, PHP, SQL, XML, Sublime Secondary Weapons: - jQuery Plugins, Social API's, Google Maps API, PSD Slicing, EXTjs, Knockout.js, jQUery UI, Visual Studio, Git Events: -&gt; SummerHacks, Timisoara 2013, hacker (bone-R project) -&gt; Coder Dojo, Timisoara, 2012 - Mentor -&gt; How to Web, Bucharest, 2012 - participant -&gt; Geekmeet 48, Timisoara 2012 - participant -&gt; Yahoo! Open Hack Europe, Bucharest, 2011 - hacker -&gt; AIESEC University - IT School, Timisoara, 2011 - participant Courses; -&gt; First Aid Provider

Updated on July 25, 2020

Comments

  • Leth
    Leth almost 4 years

    I have an array with the name of some of my variables. Don't ask why. I need to foreach() that array and use the values of it as variables names. My variables exists and contain data.

    Example:

    myArray = ["variable.name", "variable.age", "variable.genre"];
    variable.name = "Mike";
    console.log(treat_it_as_variable_name(myArray[0]));
    

    Console should now display: Mike

    Is it even possible in javascript?