How to deep copy custom object in javascript?

I surfed here and did not find the answer that worked for me.

Is there a way to deep copy a non-regular object in JS?

I tried jQuery.extend(true, {}, this) , but only cloned it, the rest remained a reference to another object.

+10
source share
4 answers

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.

+11
source

You can use the lodash function cloneDeep - https://lodash.com/docs/4.16.4#cloneDeep

Example (from documents)

 var objects = [{ 'a': 1 }, { 'b': 2 }]; var deep = _.cloneDeep(objects); console.log(deep[0] === objects[0]); // => false 
+4
source

If you are dealing with an instance of a class, you can use something like this.

You will not need to copy the functions as they are delegated to the prototype.

 // myObject constructor function myObject(foo, bar){ this.foo = foo this.bar = bar } // delegate the functions to a prototype myObject.prototype.something = function(){ console.log('something') } function instanceCopy(obj) { // copy the object by the constructor const copy = new obj.constructor() const keys = Object.keys(obj) keys.forEach(key => { copy[key] = obj[key] }) return copy } const myObj = new myObject('foo', 'bar') const copyObj = instanceCopy(myObj) console.log('myObj', myObj) console.log('copyObj', copyObj) console.log('same ?', copyObj === myObj) // can we still call the functions copyObj.something() 
 <script src="https://codepen.io/synthet1c/pen/WrQapG.js"></script> 
0
source

The Lodash _.cloneDeep () method kills application performance. So I came up with a basic JavaScript solution. I added it to the GIT repository. My application performance returned to normal after using my solution.

https://github.com/manideeppabba1991/javascript_util_functions/blob/master/clone_Array_or_Object.js

-1
source

Source: https://habr.com/ru/post/1257996/


All Articles