I've been surfing around here a while and still haven't found an answer that worked for me.
Is there any way to deep copy a non-plain object in JS?
I've tried jQuery.extend(true, {}, this)
but it only cloned some of it, the rest remained as a reference to another object.
Copy an Object With Object.assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.
According to the benchmark test, the fastest way to deep clone an object in javascript is to use lodash deep clone function since Object.
Like most other programming languages JavaScript allows supports the concept of deep copy and shallow copy. Shallow Copy: When a reference variable is copied into a new reference variable using the assignment operator, a shallow copy of the referenced object is created.
You can use lodash's cloneDeep function - https://lodash.com/docs/4.16.4#cloneDeep
Example (from docs)
var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With