AlbertMunichMar
AlbertMunichMar

Reputation: 1896

Google Script: i can not assign a value to a key of an object

I have a simple object in JS, with years as keys, and inside the months. Inside every month, I want to store information. Here is my object:

function generateYearMonths() {
  var firstYear = 2012;
  var todayDate = new Date(Date());
  var lastYear = todayDate.getYear();
  var yearsMonths = {}

  var months = {}

  for(var x=1; x<=12; x++) {
    months[x.toString()] = {
      totalExpenses: 0,
      totalIncomes: 0,
      totalBalance: 0
    }
  }

  for(var x=firstYear; x<=lastYear; x++) {
    yearsMonths[x] = months
  }

  return yearsMonths;
}

I want to assign to a year, and a month, for example year 2012, month 1, which are keys, a value. I do that:

yearsMonths[2012][1]["totalExpenses"] = 23;

And the value 23 is assigned to every year in the month 1. I don't understand where is the error. I am trying Google script for the first time, I don't know what I am doing wrong, I just want to update the hash with values. But for every year-month pair key, not overwrite every single month.

Please help.

EDIT -- move months into loop form years

function generateYearMonths() {
  var firstYear = 2012;
  var todayDate = new Date(Date());
  var lastYear = todayDate.getYear();
  lastYear = 2013;
  var yearsMonths = {}

  for(var x=firstYear; x<=lastYear; x++) {

    var months = {}

    for(var x=1; x<=12; x++) {
      months[x.toString()] = {
        totalExpenses: 0,
        totalIncomes: 0,
        totalBalance: 0
      }
    }
    yearsMonths[x] = months
  }

  return yearsMonths;
}

Now I don't assign the same value to every month, because the script runs infinitely...

Upvotes: 0

Views: 23

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371138

Objects are passed by reference in Javascript, not by value. You only ever have one var months = {} object referenced throughout the entire script, so when you do

for(var x=firstYear; x<=lastYear; x++) {
  yearsMonths[x] = months
}

every yearMonths[x] is referencing the same singular months object. Deep clone months instead, to ensure that every item in the yearMonths array references a unique object:

for(var x=firstYear; x<=lastYear; x++) {
  yearsMonths[x] = JSON.parse(JSON.stringify(months));
}

Upvotes: 1

Related Questions