0

In my app I have this line of code:

var newMatrix = this.state.matrix;

I would like to set 'newMatrix' to a copy, not a reference, of 'this.state.matrix'. 'this.state.matrix' is a 2D array populated with React components which will eventually be rendered into a grid on the screen.

What would be best practice to deep copy it into the new variable?

  • Possible duplicate of [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – Hanlet Escaño Oct 30 '17 at 21:47
  • In case it doesn't have circular references, you could use this: `var newMatrix = JSON.parse(JSON.stringify(this.state.matrix));` – Piyin Oct 30 '17 at 22:06

1 Answers1

0

The standard procedure in this cases is to just traverse your data structure and manually copying the values or copying the references of sub-objects as you see fit.

Example:

class Dog {
    constructor() {
        this.tag = {name: "foo", material: "bar"};
    }
}

function copyDog(dog) {
    let _dog = new Dog();
    _dog.tag.name = dog.tag.name;
    _dog.tag.material = dog.tag.material;
    return _dog;
}

myDog = new Dog();
yourDog = copyDog(myDog);

And thus:

> myDog == yourDog;
false

This is not the only way and much depends on your implementation and the depth at to which you wish to copy.

arielnmz
  • 8,354
  • 9
  • 38
  • 66