1

I am trying to set a variable from a key value pair where the key is the name of the variable.

Let's say I have :

var someValue = 10;

function setValue(key, value) {
  key = value; //key is the actual name of the var i.e. "sameValue"
}

So the idea is to change the value of "someValue". Is this even possible in JavaScript?

Nebula
  • 679
  • 2
  • 17
  • 37

1 Answers1

0

The better approach is to make use of a JSON object. To achieve that , you can always have a key:value JSON object where the key corresponds to your variable. See the example below. The variable someValue is actually a key of the JSON object obj then you can easily reference that to simulate as if you are calling a dynamic variable and changing its value.

var obj = {
   someValue : 10
};

function setValue(key, value) {
  obj[key] = value; //key is the actual name of the var i.e. "sameValue"
}

setValue('someValue',30);
console.log(obj['someValue']);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62