Here is my code snippet:
let traces = { ref: null, min: null, max: null, avg: null };
let learning = {
"Application": "b3",
"t": [
{
"d": 2,
"BinaryType": "Current"
},
{
"d": 3,
"BinaryType": "Max"
},
{
"d": 4,
"BinaryType": "Avg"
},
{
"d": 5,
"BinaryType": "Min"
}
]
};
let traceArr = Object.assign([],learning.t);
traceArr.forEach(trace => {
if (trace.BinaryType == 'Current') {
traces.ref = Object.assign({}, learning);
traces.ref.t = [];
traces.ref.t.push(trace);
traces.ref.t[0].BinaryType = 'Refeyrence';
}
if (trace.BinaryType == 'Min') {
traces.min = Object.assign({}, learning);
traces.min.t = [];
traces.min.t.push(trace);
}
if (trace.BinaryType == 'Max') {
traces.max = Object.assign({}, learning);
traces.max.t = []
traces.max.t.push(trace);
}
if (trace.BinaryType == 'Avg') {
traces.avg = Object.assign({}, learning);
traces.avg.t = [];
traces.avg.t.push(trace);
}
});
console.log("Output",traces);
console.log("Traces- Should be non mutated",traceArr);
console.log("Original",learning.t)
It is my belief that modifying the array contents should not affect the content of the original object (learning).
I have two questions:
- I assumed that traces.ref.t = []; would change the reference in the newly created object. However, this does not seem to be the case. Why is that?
The console.log("Original",learning.t) output shows that the content has been modified (the text Refeyrence was changed during array iteration). Why is this happening and how can I prevent it?
'Original' [ { d: 2 , BinaryType: "Refeyrence" }, { d: 3 , BinaryType: "Max" }, { d: 4 , BinaryType: "Avg" }, { d: 5 , BinaryType: "Min" } ]