My JavaScript object structure involves years as keys and months inside them to store information. The initial object looks like this:
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 am trying to set a value for a specific year and month combination, such as 2012 for year and 1 for month. I attempted the following:
yearsMonths[2012][1]["totalExpenses"] = 23;
However, the value 23 gets assigned to every month in the year 2012's object. I can't figure out what mistake I'm making. This is my first time working with Google script and I just want to update specific key-value pairs without overwriting everything.
Your assistance would be greatly appreciated.
EDIT -- Restructuring months within the loop for each year
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;
}
By moving the month creation logic inside the yearly loop, I no longer encounter infinite loops while assigning values individually for each month.