1

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?

Run_Script
  • 2,487
  • 2
  • 15
  • 30

2 Answers2

2

U just need to use a spread operator.

var objectArray1 = [
  {number:1, color:'red'},
  {number:4, color:'blue'}
];

var objectArray2 = JSON.parse(JSON.stringify(objectArray1 ));

objectArray2[0].number = 7;
console.log(objectArray1);
Ivan S
  • 61
  • 5
2

To do a clone of this you just need to do

var objectArray1 = [
  {number:1, color:'red'},
  {number:4, color:'blue'}
];

var objectArray2 = JSON.parse(JSON.stringify(objectArray1));

And this will actually create a new copy of the objects and not just reference them and you should be able to work on the separately like you want.

Odinn
  • 808
  • 5
  • 23