Here are 3 different methods for copying objects. Each method has its pros and cons, so read and choose the best for your situation.
Object.assign Method
Use Object.assign , which "is used to copy the values ββof all enumerated own properties from one or more source objects to the target object." This copies both values ββand functions. At the time of this writing, browser support was good, but not perfect, but this is the best IMO of the three.
const obj1 = {a:1, b:2}; const obj1Copy = Object.assign(obj1)
Distribution Operator Method
Alternatively, you can use the spread operator to spread from one object to another. Keep in mind that this will copy the key values, but if the key value is a memory address (another nested object or array), then it will only be a shallow copy.
const obj1 = {a: () => {}, b:2} const obj1Copy = { ...obj1 }
JSON stringify / parse trick
If the object does not have circular references or functions as values, you can use the json stringify trick:
let myCopy = JSON.parse(JSON.stringify(myObject));
Libraries are not required, and works very well for most objects.
source share