4

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?

Leth
  • 145
  • 1
  • 1
  • 12

4 Answers4

12

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]

Tahir Akhtar
  • 11,385
  • 7
  • 42
  • 69
3

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]]);
}
cdhowie
  • 158,093
  • 24
  • 286
  • 300
1

You could parse the variable yourself:

var t = myArray[0].split(".");
console.log(this[t[0]][t[1]]);
laurent
  • 88,262
  • 77
  • 290
  • 428
1

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.

Community
  • 1
  • 1
hmakholm left over Monica
  • 23,074
  • 3
  • 51
  • 73