Haris Khan
Haris Khan

Reputation: 171

javascript: when looping again through array, I want object property to reset

I am trying to make an object, where the keys are number of years and value is amount of money

vm.argiterraYearlyLocalCost = {"2016":0,"2017":0,"2018":0,"2019":0} //year(key):amount(value)

I have an input field in the view, that lets me make new amount and everytime I add different addLocalCostContributor and it will check if the condition matches,the amount will be added to the year.

function addLocalCostContributor(localCost, year) {
        localCost.contributors.push({});

          for(var i=0; i < localCost.contributors.length;i++ ) {
            if(angular.isDefined(localCost.contributors[i].contributor) && localCost.contributors[i].contributor.name ==='Agriterra') {
              var amount = parseInt(localCost.contributors[i].amount);
              vm.argiterraYearlyLocalCost[year] = parseInt(vm.argiterraYearlyLocalCost[year] || 0) + amount;
            }
          }
    }

vm.argiterraYearlyLocalCost = {};//ths is intiliased in the top of angular controller

Problem is that whenever new amount is added and conditions are met, the amount increments but it starts the loop all over again. For example I add firstAmount, it gives me {'2016' : firstAmount}, but when I add newAmount and submit it starts loop again and it gives {'2016': firstAmount + firstAmount + newAmount}, while all I want is firstAmount + newAmount. If i can reset the vm.argiterraYearlyLocalCost[year] everytime I submit (and the function loops to increment the property) I will get the right answer. looping problem when logged I can't think clearly how and where to reset this property, if some one can see from different eyes.

Upvotes: 0

Views: 185

Answers (1)

Arnelle Balane
Arnelle Balane

Reputation: 5487

Try resetting the amount for that year before the for loop runs.

function addLocalCostContributor(localCost, year) {
    localCost.contributors.push({});

    vm.argiterraYearlyLocalCost[year] = 0; // <= added this line

    for (var i = 0; i < localCost.contributors.length; i++) {
        if (angular.isDefined(localCost.contributors[i].contributor) 
        && localCost.contributors[i].contributor.name === 'Agriterra') {
            var amount = parseInt(localCost.contributors[i].amount);
            vm.argiterraYearlyLocalCost[year] = parseInt(vm.argiterraYearlyLocalCost[year] || 0) + amount;
        }
    }
}

vm.argiterraYearlyLocalCost = {};

Upvotes: 2

Related Questions