The array changes its value even though it was pushed earlier
var original =
[{
a: 1,
data:
{ b: 'before' }
},
{
a: 2,
data:
{ b: 'before' }
}];
var arr1 = [];
var arr2 = [];
for(i=0; i<original.length; i++) {
let value = original[i];
//pushed earlier
arr1.push(value);
let newvalue = original[i];
if (newvalue.data.b == "before") {
newvalue.data.b = "after";
arr2.push(newvalue);
}
}
console.log("ARRAY 1 ");
console.log(arr1);
console.log("ARRAY 2 ");
console.log(arr2);
produces
ARRAY 1
[ { a: 1, data: { b: 'after' } }, { a: 2, data: { b: 'after' } } ]
ARRAY 2
[ { a: 1, data: { b: 'after' } }, { a: 2, data: { b: 'after' } } ]
I am guessing this has something to do with how JS changes the value since it is being reference by the original array itself.
Whats the optimal solution in such cases where you have to retain the original array while use it to modify and create another array?