Lodash | _.cloneDeep() Method

The _.cloneDeep() method is used to create a deep copy of the value i.e. it recursively clones the value. This method is similar to the _.clone() method.

Syntax:

_.cloneDeep( value )

Parameters: This method accepts single parameter as mentioned above and described below:

  • value: This parameter holds the value that need to be clone recursively.

Return Value: This method returns the deep cloned value.

Example 1: Cloning Simple Object



filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
  
var obj = {
    x: 23
};
  
// Deep copy
var deepCopy = _.cloneDeep(obj);
  
console.log('Comparing origianal with'
    + ' deep ', obj === deepCopy);
  
obj.x = 10; // Changing original value
  
console.log('After changing original value');
  
console.log("Original value ", obj);
  
console.log("Deep Copy value ", deepCopy);

chevron_right


Output:

Comparing origianal with deep  false
After changing original value
Original value  { x: 10 }
Deep Copy value  { x: 23 }

Example 2: Cloning complex object

filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
   
var obj = [{  x: 1 }, {y: 2}];
  
// Deep copy
var deepCopy = _.cloneDeep(obj);
   
console.log('Comparing origianal with deep ',
            obj[0] === deepCopy[0]);
   
// Changing orignal value
obj[0].x = 10;
   
// Values after changing original value
console.log("After changing original value");
   
console.log("Original value ", obj);
   
console.log("Deep Copy value ", deepCopy);

chevron_right


Output:

Comparing origianal with deep  false
After changing original value
Original value  [ { x: 10 }, { y: 2 } ]
Deep Copy value  [ { x: 1 }, { y: 2 } ]

So, here we have seen that after changing original value the deep copy of the values didn’t change because _.cloneDeep() recursively copied the value deeply.

Note: This will not work in normal JavaScript because it requires the library lodash to be installed.

Reference: https://lodash.com/docs/4.17.15#cloneDeep

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.