JRebo JRebo - 2 months ago 10
Javascript Question

Using a string stored in a variable as a name for another variable

I want to concatenate a string passed as argument with another word and then use it as a variable name for an array. Is this allowed?

function getFromSomewhere(arg1) {

string newName = arg1 + "sampleWord";

var (use NewName here) = [];

}

Answer Source

Yes it is possible. But no, you dont want to do that. Dynamic variable names are always a sign, that you should use an object instead. In this case i think you could simply map your array of strings to an array of objects:

 function namesToObj(arr){
   return arr.map( name => ({
    name,
    price:10
   }));
}

 namesToObj(["banana","tomato"])
 /*results in
 [{name:"banana",price:10},{name:"tomato",price:10}]
 */