I create an object name month, List year and object list. Then I add list year to object list as keys and add object month to list of object list.
var year = [2021, 2020];
var month = {"jan": 0, "feb": 0, "mar": 0};
var list={};
for (let i = 0; i < 2; i++) {
list[year[i]] = [month];
}
list['2021'][0]['feb']+=1;
console.log(list);
Result: list={'2021': [{'jan':0, 'feb':0, 'Mar':0}], '2020': [{'jan':0, 'feb':0, 'Mar':0}]}
Results as I wanted, but problem occurred when I try to increment the value of each month by year.
Example: list['2021'][0]['feb']+=1;
What I want: list={'2021': [{'jan':0, 'feb':1, 'Mar':0}], '2020': [{'jan':0, 'feb':0, 'Mar':0}]}
What I get: list={'2021': [{'jan':0, 'feb':1, 'Mar':0}], '2020': [{'jan':0, 'feb':1, 'Mar':0}]}
montharray, and you've just stored two references to that array. If you dolist[year[i]] = [{"jan": 0, "feb": 0, "mar": 0}];instead of usingmonth, it should work.list[year[i]] = [month];tolist[year[i]] = [{...month}];and it should work (this will basically clone the month into a new object, instead of having the same object in bothvar month = {...}line inside theforloop