Lodash | _.clone() Method

The _.clone() method is used to create a shallow copy of the value. This method supports cloning arrays, array buffers, booleans, date objects, maps, numbers, Object objects, regexes, sets, strings, symbols, and typed arrays. It is loosely based on the structured clone algorithm.

Syntax:

_.clone( value )

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

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

Return Value: This method returns the shallow copy of value.

Example 1: Cloning Simple Object



filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
  
var obj = {
    x: 23
};
  
// Shallow copy
var shallowCopy = _.clone(obj);
  
console.log('Comparing original with'
    + ' shallow ', obj === shallowCopy);
  
obj.x = 10; // Changing original value
  
console.log('After changing original value');
  
console.log("Original value ", obj);
  
console.log("Shallow Copy value ", shallowCopy);

chevron_right


Here, const _ = require('lodash') is used to import the lodash library into the file.

Output:

Comparing original with shallow  false
After changing original value
Original value  { x: 10 }
Shallow 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}];
  
// Shallow copy
var shallowCopy = _.clone(obj);
   
console.log('Comparing original with shallow ',
            obj[0] === shallowCopy[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("Shallow Copy value ", shallowCopy);

chevron_right


Output:

Comparing original with shallow  true
After changing original value
Original value  [ { x: 10 }, { y: 2 } ]
Shallow Copy value  [ { x: 10 }, { y: 2 } ]

So, here we have seen that after changing original value the shallow copy value also changed because _.clone() doesn’t copy deeply it just passed the reference.

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#clone

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.