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?

share|improve this question
Will the strings in the array always refer to the same variable.? (i.e. only the last part, the property, differs) – Felix Kling Aug 17 '11 at 11:59
you wont to rename variables? – Haroldis Aug 17 '11 at 11:59

4 Answers

up vote 3 down vote accepted

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
share|improve this answer

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]]);
}
share|improve this answer

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|improve this answer

You could parse the variable yourself:

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

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.