Leth Leth - 4 months ago 8
Javascript Question

javascript array with names of variables

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?

Answer

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]