-2

I'm trying to copy an object in other using spread operator but wheni change one item from array in a copy object, the original is changed to. Any one knows how can i make the change only in object 2 ?

Follow a simple example:

let obj1 = { a:'hello', b:'hi', c: [1,2,3] }
let obj2 = { ...obj1 }
obj2.c[1] = 44 

EDIT: This thread has the answer :) What is the most efficient way to deep clone an object in JavaScript?

1 Answers1

1

The most common and secure method is through Object.assign():

let clone = Object.assign({}, myObj);

It creates a shallow copy, if you want a deep copy you can use lodash deepClone(), for example or write yourself a recursive cloner.

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43