Open In App
Related Articles

Lodash _.cloneDeep() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Lodash _.cloneDeep() method is used to create a deep copy of the value and it recursively clones the value. The newly created object has the same value as the original but they are not the same object in the 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 } ] 


Last Updated : 18 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads