Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deep copy a custom object in JavaScript?

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.

like image 566
Robmeister2015 Avatar asked Oct 10 '16 23:10

Robmeister2015


People also ask

How do you deeply clone an object in JavaScript?

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.

What is the most efficient way to deep clone an object in JavaScript?

According to the benchmark test, the fastest way to deep clone an object in javascript is to use lodash deep clone function since Object.

Does JavaScript have deep copy?

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.


1 Answers

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
like image 64
Felipe Sabino Avatar answered Oct 03 '22 16:10

Felipe Sabino