fahad
fahad

Reputation: 13

Javascript: New variable name composed of value of another variable

Easiest to explain by showing code:

var delta_selected = false;
var magma_selected = false;
var aqua_selected = false;

// Somewhere in my functions...
if (sumthing == 'sumthing1') {
    topic = 'delta';
} else if (sumthing == 'sumthing2') {
    topic = 'magma';
} else {
    topic = 'aqua';
}

// Then assign it (so if topic is delta, then delta_selected = true)
topic + "_selected" = true;

This last line isn't working. Syntax error.

I need help to figure out how to do this. Thanks!

Upvotes: 0

Views: 649

Answers (3)

user1106925
user1106925

Reputation:

Why use variables? Looks to me like you need a single structure that contains all your _selected values.

var selected = {
    delta:false,
    magma:false,
    aqua:false
};

then...

if (sumthing == 'sumthing1') {
    topic = 'delta';
} else if (sumthing == 'sumthing2') {
    topic = 'magma';
} else {
    topic = 'aqua';
}

selected[topic] = true;

Upvotes: 3

cjstehno
cjstehno

Reputation: 13984

Take a look at the "eval()" function. You will probably end up with something like:

eval(topic + "_selected = true;")

But check the documentation to be sure.

Hope this helps.

Upvotes: 0

Marshall
Marshall

Reputation: 4766

try this

window[topic + "_selected"] = true;

Upvotes: 3

Related Questions