How to create deep object with dynamic name in Javascript?

How do you dynamically name and create an object in javascript?

  • normally to create an object you would write: function Dog(name) { this.name = name; } fifi = new Dog("fifi"); How do I dynamically name the object so that I can write: var name = "fifi"; [name] = new Dog(name); to achieve the same outcome as: fifi = new Dog("fifi");

  • Answer:

    If you know the object you're creating the variable on (a property, not just a variable) you can use https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators#Bracket_notation, like this: var dogs = {}; dogs[name] = new Dog(name); Later you could access it either way: dogs.fifi //or... dogs["fifi"] If it's a global variable you're after, that object (instead of dogs above) would just be window.

Anthony H at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

This would do it: function createDog(name, scope) { scope[name] = new Dog(name); } Then you could do: createDog('fifi', window); or pass any other object as your scope. But I would not tie objects and variables to close together. One advantage of objects is that you can pass them freely around and several variables can have a reference to the same object. I would give it a more meaningful name, that describes the purpose of that object.

Felix Kling

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.