I have an array of objects called objectArray1
. I would like to set a second variable, objectArray2
, to the value of this first array, and then be able to change it independently.
Here is the code I tried:
var objectArray1 = [
{number:1, color:'red'},
{number:4, color:'blue'}
];
var objectArray2 = objectArray1;
objectArray2[0].number = 7;
console.log(objectArray1);
However, as you can see from the above snippet, changing a value in objectArray2
also changes the same value in objectArray1
(the 1
changes to a 7
).
I found some other questions on stackoverflow about this, such as Setting one object equal to another object with the assignment operator in Javascript, but they are all just about objects and not arrays of objects, so I haven't been able to apply them to my case.
To try and fix my issue, I tried some new code which I hoped would work better:
var objectArray1 = [
{number:1, color:'red'},
{number:4, color:'blue'}
];
var objectArray2 = [];
for (i = 0; i < objectArray1.length; i++) {
objectArray2.push(objectArray1[i]);
}
objectArray2[0].number = 7;
console.log(objectArray1);
However, the same thing still happens (the 1
still changes to a 7
). How do I solve this?