Skip to content
Related Articles

Related Articles

Lodash | _.cloneDeep() Method
  • Last Updated : 08 May, 2020

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






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);

Output:

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

Example 2: Cloning complex object




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);

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :