javascript – Simplify multiples "else if" based on the value of a string variable

Question:

The following code works and has 4 conditions but I want to simplify it since it is actually 150 conditions, is there any other way to reduce this algorithm and other than 150 else if?

for (var j = 0; j < $scope.cants.length; j++) {
  if ($scope.cants[j].type === "bases") {       
    $scope.bases += $scope.cants[j].quantity;
  } else if ($scope.cants[j].type === "proteins") {     
    $scope.proteins += $scope.cants[j].quantity;
  } else if ($scope.cants[j].type === "veggies") {      
    $scope.veggies += $scope.cants[j].quantity;
  } else if ($scope.cants[j].type === "sauces") {       
    $scope.sauces += $scope.cants[j].quantity;
  } 
  $scope.componentsPlate = $scope.proteins +  $scope.veggies + $scope.sauces +     $scope.dryfruits + $scope.bases + $scope.proteinsExtra +        $scope.veggiesExtra + $scope.saucesExtra + $scope.dryfruitsExtra +  $scope.basesExtra
}

Answer:

The syntax:

$scope.nombreDePropiedad

It is equivalent to:

$scope["nombreDePropiedad"]

Which you can take advantage of to use it in the following way:

for (var j = 0; j < $scope.cants.length; j++) {
    $scope[$scope.cants[j].type] += $scope.cants[j].quantity;
}

This way you don't need to do any if or switch since the correct member of the $scope object will be selected from the string that you pass between brackets.

Scroll to Top