Lodash _.cloneDeep() Method

The Lodash _.cloneDeep() method is handy for making a complete copy of a value. It goes deep into the value, copying everything inside it too. So, the new object you get has the exact same data as the original, but they’re not linked in memory.

This method is similar to the _.clone() method.

Syntax: 

_.cloneDeep(value);

Parameters:

  • value parameter holds the value that needs to be cloned recursively.

Return Value:

This method returns the deep-cloned value

Example 1: In this example, It is returning false because they both have the same value but different memory allocations, and the “===” operator checks for the same reference in objects

Javascript
const _ = require('lodash');

let obj = {
    x: 23
};
// Deep copy 
let 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: In this example, It is returning false because they both have the same value but different memory allocations, and “===” operator checks for the same reference in objects and we can change the original object it will not change the cloned object’s value as both of them have different memory allocation

Javascript
const _ = require('lodash');

let obj = [{ x: 1 }, { y: 2 }];

// Deep copy 
let 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 } ]