-1

According with what was sayed on another question:

The spread operator is like Object.assign and does not deeply clone an object. The reason the JSON thing worked is because you created a whole new object which would pass the strict equality check, however all your components would update needlessly because nothing will pass a strict equality check now.

Object.assign({}, ...prevState, ...newState) would create a new top-level object, but it would not create a new object for any objects nested in prevState or newState. However, you would have to carefully update nested objects so as to avoid needless re-renders. This can get tricky for deeply nested objects and arrays.

My question is.... what must we do when we need to return a new version of an object that have properties tha contains arrays? For example:

const foo = {
  myArray: [1, 2, 3],
  name: 'Hello world'
};

const clonedObj = { ...foo }

This will create a new object with a copy of name and it's content, a copy of myArray key BUT not with a copy of [1, 2, 3].

JSON.parse + JSON.stringify does the trick but don't look like a clean way.

What alternative do I have?

Thank you

1 Answers1

-2
const clonedObj = Object.assign({}, foo);

Object.assign

Anuja
  • 124
  • 2
  • 6
  • 2
    Consider reading the question more closely before answering. Not only does it quite clearly discuss the need for a "deep" copy, it specifically calls out `Object.assign` as not working for deep copy (which it doesn't). – T.J. Crowder Jul 25 '17 at 08:43