Note: subObj, subObj2, subObj3, subObj4 are all objects {}
Here is the code:
for (var key in subObj) {
if (subObj.hasOwnProperty(key)) {
subObj2 = subObj[key];
subObj3["player"] = subObj2["player"];
subObj3["bodypart"] = subObj2["bodypart"];
subObj3["type"] = subObj2["type"];
subObj3["result"] = subObj2["result"];
aux = subObj2["zone"];
//WARNING: here is the problem. All object content (except keys) are being set to subObj3
console.log(subObj4);
//initialize > important! (this creates new properties in object)
if (!subObj4.hasOwnProperty(aux)) {
subObj4[aux] = {};
}
if (!subObj4[aux].hasOwnProperty(key)) {
subObj4[aux][key] = {};
}
//store
subObj4[aux][key] = subObj3;
console.log("aux = ", aux, " key = ", key);
console.log(subObj3);
console.log(subObj4);
} //endif
} //endfor
Console Logs
current output:
1st loop:
//log of "aux" and "key"
aux = e3c , key = 1
//log of "subObj3"
{player: "john", bodypart: "h", type: "open_t", result: "correct"}
//log of "subObj4"
{e3c:{
1:{player: "john", bodypart: "h", type: "open_t", result: "correct"}
}
}
2nd loop:
//log of "aux" and "key"
aux = e3c , key = 4
//log of "subObj3"
{player: "robert", bodypart: "lf", type: "open_t", result: "incorrect"}
//log of "subObj4"
{e3c:{
1:{player: "robert", bodypart: "lf", type: "open_t", result: "incorrect"}
4:{player: "robert", bodypart: "lf", type: "open_t", result: "incorrect"}
}
}
expected output:
//log of "subObj4"
{e3c:{
1:{player: "john", bodypart: "h", type: "open_t", result: "correct"}
4:{player: "robert", bodypart: "lf", type: "open_t", result: "incorrect"}
}
}
After more debugging i found were the object is changing its values (its commented in the code with a "Warning"). Is in that line that all the object values change