0

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}]}

3
  • Right. You have one month array, and you've just stored two references to that array. If you do list[year[i]] = [{"jan": 0, "feb": 0, "mar": 0}]; instead of using month, it should work. Commented Jan 20, 2023 at 7:25
  • change list[year[i]] = [month];to list[year[i]] = [{...month}]; and it should work (this will basically clone the month into a new object, instead of having the same object in both Commented Jan 20, 2023 at 7:27
  • Or move the var month = {...} line inside the for loop Commented Jan 20, 2023 at 8:10

1 Answer 1

0

Try This

var year = [2021, 2020];
var month = {"jan": 0, "feb": 0, "mar": 0};
var list={};
for (let i = 0; i < 2; i++) {
    list[year[i]] = [Object.assign({}, month)];
}
list['2021'][0]['feb']+=1;
console.log(list);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.