0

Apologies if this is simple. I just couldn't figure-out how to do it. Searched on this site on how to dynamically change variables and evaluate them etc but can't figure out how to do what I want.

Problem: I have a variable that I set to a value:

vm.toggleDrop = function($switchToggle){
        vm.switchValue = "switch"+$switchToggle;
        //Here 

    };

Where it says "Here", I need to instantiate a new variable that is called whatever is the result if the above statement eg; switch1 then set it true or false as a boolean. eg: switch1 = false; Therefore again, if $switchToggle parameter was "Test", I need to dynamically create a variable called switchTest and set it true or false.

Is such a thing possible ? Thanks all

Afshin Ghazi
  • 2,784
  • 4
  • 23
  • 37
  • 1
    Already answered here I believe : http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript – nastyklad Jun 29 '16 at 13:45

2 Answers2

1

Something like that?(I created vm variable just for code snippet, ignore it)

var vm = {};

vm.toggleDrop = function($switchToggle){
        vm.switchValue = "switch"+$switchToggle;
        vm[vm.switchValue] = 'whatever';
        console.log(vm);
    };

vm.toggleDrop('true');

Also if you do not need to attach variable to vm object, best answer will be @nastyklad provided(using window[vm.switchValue]

Luger
  • 2,090
  • 1
  • 13
  • 11
1

Something like this:

function setVariable(name){
    var variableName = 'switch' + name;
    vm[variableName] = true;
}
Jeremy Jackson
  • 2,247
  • 15
  • 24