0

I am attempting to use the spread operator to copy an object with nested objects.

An example of my code looks like this:

constructor(props) {
    super(props)
    this.state = {
        copy1: {...this.props.originalObject},
        copy2: {...this.props.originalObject}
    }

This works fine for the outer object values. Hewever, when I make changes to the nested objects in copy1, they are also changed in copy2. This tells me that it still copying the inner objects by reference. What can I do to get around this?

Duplicate Answer?

This question that was linked as a duplicate to my question does not really seem to help as it is geared towards a specific situation and is using Redux. I am not using Redux.

kojow7
  • 10,308
  • 17
  • 80
  • 135
  • @AlexanderNied This answer you linked as a duplicate does not really seem to help as it is geared towards a specific situation and is using Redux. I am not using Redux. – kojow7 Jul 24 '17 at 16:26
  • 2
    You can try [this](https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge) one as well. But ultimately, in my opinion, none of these questions is particularly related to the surrounding library, but more if (and how) a deep-copy of an object can be accomplished with ES6. Unfortunately, the answer appears to be that it is _not_ natively supported. You'll most likely either need to spin your own recursive solution or find a library to assist you. – Alexander Nied Jul 24 '17 at 16:31
  • Yes, as per ECMAScript spec, it only does a shallow copy of the object. You will have to implement your own or use a library with a deep-copy implementation. – mhodges Jul 24 '17 at 16:35
  • @kojow7 -- I don't wish to beat a dead horse, but the linked duplicate is, ultimately "Is there a way in ES6 to use the spread sign to deep copy an object?". That is a quote from the post. The context of Redux is only that Redux requires object copies, just like you require an object copy in your scenario. And the selected answer makes no mention of Redux whatsoever-- only referencing the question regarding ES6 object deep copies. I think you'll find it still pertains to what you are seeking. – Alexander Nied Jul 24 '17 at 17:13

0 Answers0