The _.snapshot() method is used to snapshot or clone a given object deeply.
Syntax:
_.snapshot( obj );
Parameters: This method takes an object to create a deep clone.
Return Value: This method returns a clone object.
Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed.
Underscore.js contrib library can be installed using npm install underscore-contrib –save.
Example 1:
Javascript
// Defining underscore contrib variable var _ = require( 'underscore-contrib' ); var given_Object = { 1: "a" , 2: "b" }; var obj = _.snapshot(given_Object);; console.log( "Cloned Object: " , obj); |
Output:
Cloned Object: { '1': 'a', '2': 'b' }
Example 2: This method works well for an array also.
Javascript
// Defining underscore contrib variable var _ = require( 'underscore-contrib' ); var given_Object = [ 1, 2 ,3 ,4 ]; var obj = _.snapshot(given_Object);; console.log( "Cloned Object: " , obj); |
Output:
Cloned Object: [ 1, 2, 3, 4 ]
Example 3: This method works for strings also.
Javascript
// Defining underscore contrib variable var _ = require( 'underscore-contrib' ); var given_Object = "neveropen" var obj = _.snapshot(given_Object);; console.log( "Cloned Object: " , obj); |
Output:
Cloned Object: neveropen
Example 4:
Javascript
// Defining underscore contrib variable var _ = require( 'underscore-contrib' ); var given_Object = 10000; var obj = _.snapshot(given_Object);; console.log( "Cloned Object: " , obj); |
Output:
Cloned Object: 10000