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
javascript
const _ = require( 'lodash' );
var obj = {
x: 23
};
var shallowCopy = _.clone(obj);
console.log( 'Comparing original with'
+ ' shallow ' , obj === shallowCopy);
obj.x = 10;
console.log( 'After changing original value' );
console.log( "Original value " , obj);
console.log( "Shallow Copy value " , shallowCopy);
|
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
javascript
const _ = require( 'lodash' );
var obj = [{ x: 1 }, {y: 2}];
var shallowCopy = _.clone(obj);
console.log( 'Comparing original with shallow ' ,
obj[0] === shallowCopy[0]);
obj[0].x = 10;
console.log( "After changing original value" );
console.log( "Original value " , obj);
console.log( "Shallow Copy value " , shallowCopy);
|
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