SUMMARY: A write operation to a single value in a JS Object (JSON format) modifies two values. (probably a copy vs reference bug).
UPDATE: JSFiddle with basic version of bug: https://jsfiddle.net/J_withfeeling/vmhx95yL/
FULL QUESTION:
I want to prep some data client side before writing it to a server.
I create my object like so:
let number = {};
let category = {};
number = {
"numbers":{
"num1":0,
"num2":0,
"num3":0
}
};
console.log(categories);//confirming that categories is "{"category1":true,"category2":true}"
for(let m in majorList){//initialize the JSON object
category[m] = Object.assign({}, number);
}
data = {major};
I now have a nice JS object, constructed in a JSON format:
{
"category":{
"category1":{
"numbers":{
"num1":0,
"num2":0,
"num3":0
}
},
"category2":{
"numbers":{
"num1":0,
"num2":0,
"num3":0
}
}
}
I'm able to console.log(data) properly at this point with no problems.
Then with some JS I want to update the "num" values. I do this right now:
//some stuff up here to figure out which "category" and "number" to increment
console.log(cat);
console.log(num);
console.log(JSON.stringify(data));
data['category'][cat]['numbers'][num] = data['category'][cat]['numbers'][num] + 1;
console.log(JSON.stringify(data));
//the above 5 lines are executed multiple times in a loop
What I expect to print out of those console.log statements is something like this:
category1
num2
"myJSON":{
"category":{
"category1":{
"numbers":{
"num1":0,
"num2":0,
"num3":0
}
},
"category2":{
"numbers":{
"num1":0,
"num2":0,
"num3":0
}
}
}
}
"myJSON":{
"category":{
"category1":{
"numbers":{
"num1":0,
"num2":1,
"num3":0
}
},
"category2":{
"numbers":{
"num1":0,
"num2":0,
"num3":0
}
}
}
}
What actually prints out is this:
category1
num2
"myJSON":{
"category":{
"category1":{
"numbers":{
"num1":0,
"num2":0,
"num3":0
}
},
"category2":{
"numbers":{
"num1":0,
"num2":0,
"num3":0
}
}
}
}
"myJSON":{
"category":{
"category1":{
"numbers":{
"num1":0,
"num2":1,
"num3":0
}
},
"category2":{
"numbers":{
"num1":0,
"num2":1,
"num3":0
}
}
}
}
The "num2" value is getting incremented in both of the "category" keys, in just a single pass of the innermost for loop. Why?
Admittingly above this code snippet there is a little more going on, but it's a bit much to include in a stackoverflow question. What is definitely the case is those 4 console.logs() with the one line of code in between. Those 5 lines are copied as-is, and I don't understand how one write operation can edit multiple values in the JSON object.