Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript use variable as object name

Tags:

javascript

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'; 
like image 953
PeeHaa Avatar asked May 21 '11 22:05

PeeHaa


People also ask

Can a variable be a name in JavaScript?

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.

Can you use a variable to name an object in Java?

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?

How do you use a variable to access the object property?

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] .


2 Answers

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({}); 
like image 160
Shaz Avatar answered Sep 28 '22 02:09

Shaz


Use square bracket around variable name.

var objname = 'myobject'; {[objname]}.value = 'value'; 
like image 29
Vaishali Venkatesan Avatar answered Sep 28 '22 00:09

Vaishali Venkatesan