Javascript use variable as object name
Solution 1:
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({});
Solution 2:
Use square bracket around variable name.
var objname = 'myobject';
{[objname]}.value = 'value';