0

I'm looking to call a constructor function dynamically based on an value I have in an object.

Let's say I have an object:

var food = {

  pizzas:[
    {
      pizza: 'Pepperoni'
    },
    {
      pizza: 'Vegetarian'
    }
  ]

}

Now, let's say I have a couple of Constructor functions bound to a global object.

window.pizzaConstructors.Pepperoni = function(){
  // do something
}

window.pizzaConstructors.Vegetarian = function(){
  // do something else
}

What I want to be able to do is cycle through the food.pizzas array and call the corresponding constructor function based on the type of pizza of the current index.

So, if I have:

(for pizza in food.pizzas){
  var currentPizza = food.pizzas[pizza]

  new pizzaConstructors.currentPizza(); 
}

Any idea how I can go about this?

Modermo
  • 1,852
  • 2
  • 25
  • 46

1 Answers1

0

Use [] syntax to access the constructors.

(for pizza in food.pizzas){
  var currentPizza = food.pizzas[pizza]

  new pizzaConstructors[currentPizza](); 
}

This new pizzaConstructors.currentPizza() means call the named currentPizza function.

This new pizzaConstructors[currentPizza.pizza]() means evaluate the currentPizza, get it's value, call the function with the named of the evaluated currentPizza.

var food = {
  pizzas:[
    {
      pizza: 'Pepperoni'
    },
    {
      pizza: 'Vegetarian'
    }
  ]
};

const pizzaConstructors = {};

pizzaConstructors.Pepperoni = function(){};
pizzaConstructors.Vegetarian = function(){};

const arrOfObjects = [];

for (pizza in food.pizzas) {
  const currentPizza = food.pizzas[pizza].pizza;

  arrOfObjects.push(new pizzaConstructors[currentPizza]()); 
}

console.log(arrOfObjects);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112