I am curious if it is possible to set the name of an object in Javascript to a variable value. So if I declare a variable objectName and want to create a new object whose name is the value of objectName.
Asked
Active
Viewed 109 times
1
-
Could you maybe give an example of how you imagine it would work? The description is little vague. – Viele Jan 16 '16 at 19:22
-
Look [here](http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript) – Volodymyr Chumak Jan 16 '16 at 19:24
-
Thanks @Slam, thats perfect. – SeanBallentine Jan 16 '16 at 19:28
1 Answers
2
Try this:
var objectName = "myObjectName";
window[objectName] = {
foo: "bar"
};
console.log(myObjectName); // { foo: 'bar'}
All global variables are properties of the window object, and since window is an object, we can create a dynamic property using []
syntax. And then you can access it as window.myObjectName
, window["myObjectName"]
or just plain myObjectName
More info of window object here: http://www.w3schools.com/js/js_window.asp and here https://developer.mozilla.org/es/docs/Web/API/Window/window

Marcos Casagrande
- 37,983
- 8
- 84
- 98