1

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.

SeanBallentine
  • 173
  • 1
  • 2
  • 8

1 Answers1

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