I want to use the value of a variable to access an object.
Let's say I have an object named myobject.
I want to fill a variable with this name and use the variable to access the object.
Example:
var objname = 'myobject'; {objname}.value = 'value';
JavaScript IdentifiersIdentifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs. Names must begin with a letter.
You can't. Neither you need to. Can you explain why you tagged this question with C# or C if you want a Java solution?
Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .
Global:
myObject = { value: 0 }; anObjectName = "myObject"; this[anObjectName].value++; console.log(this[anObjectName]);
Global: v2
var anObjectName = "myObject"; this[anObjectName] = "myvalue" console.log(myObject)
Local: v1
(function() { var scope = this; if (scope != arguments.callee) { arguments.callee.call(arguments.callee); return false; } scope.myObject = { value: 0 }; scope.anObjectName = "myObject"; scope[scope.anObjectName].value++; console.log(scope.myObject.value); })();
Local: v2
(function() { var scope = this; scope.myObject = { value: 0 }; scope.anObjectName = "myObject"; scope[scope.anObjectName].value++; console.log(scope.myObject.value); }).call({});
Use square bracket around variable name.
var objname = 'myobject'; {[objname]}.value = 'value';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With