mike
mike

Reputation: 1546

Setting a variable name with another variable value - Java Script

I want to get a value from a variable then use that as the name for another variable. I got something like this:

var eval(BodyWeight[i]["ExerciseTitle"]) = BodyWeight[i]["ExerciseVideo"]; 

This is giving me an error, 'missing ; before statement'.

Any ideas?

Upvotes: 1

Views: 2905

Answers (3)

outis
outis

Reputation: 77400

While eval will give you a form of variable variables, it's messy and potentially leads to syntax errors:

try {
    eval('var ' + BodyWeight[i]["ExerciseTitle"] + ' = BodyWeight[i].ExerciseVideo');
} catch () {
    // what to do here if BodyWeight[i]["ExerciseTitle"] isn't a valid variabe name?
}

Better to use object properties rather than local variables.

thing[BodyWeight[i].ExerciseTitle] = BodyWeight[i].ExerciseVideo;

Upvotes: 2

scunliffe
scunliffe

Reputation: 63588

If I understand what you are hoping to accomplish:

var eval(BodyWeight[i]["ExerciseTitle"]) = BodyWeight[i]["ExerciseVideo"]; 

//to try and get
var BodyWeight4ExerciseTitle = BodyWeight[i]["ExerciseVideo"];
              ^-//guessing this is an iterator

To accomplish this, just do:

var key = 'BodyWeight' + i + 'ExerciseTitle';
window[key] = BodyWeight[i]["ExerciseVideo"];

//now you have a global variable "BodyWeight4ExerciseTitle"

Upvotes: 0

Jonathon Faust
Jonathon Faust

Reputation: 12545

It will be easier if you specify the part you currently have enclosed in eval as a property.

var myvar = {};
myvar[BodyWeight[i]["ExerciseTitle"]] = BodyWeight[i]["ExerciseVideo"];

No evil eval necessary.

Upvotes: 2

Related Questions