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
Javascript
const _ = require( 'lodash' ); var obj = { x: 23 }; // Deep copy var deepCopy = _.cloneDeep(obj); console.log( 'Comparing original 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 original with deep false After changing original value Original value { x: 10 } Deep Copy value { x: 23 }
Example 2: Cloning complex object
Javascript
const _ = require( 'lodash' ); var obj = [{ x: 1 }, {y: 2}]; // Deep copy var deepCopy = _.cloneDeep(obj); console.log( 'Comparing original with deep ' , obj[0] === deepCopy[0]); // Changing original 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 original 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 the 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
Please Login to comment...