Lodash To Deep Copy
Lodash is a JavaScript library that provides multiple utility functions and one of the most commonly used functions of the Lodash library is the cloneDeep() method. This method helps in the deep cloning of an object and also clones the non-serializable properties which were a limitation in the JSON.stringify() approach.
Code Implementation:
Javascript
const lodash = require( 'lodash' ); let employee = { eid: "E102" , ename: "Jack" , eaddress: "New York" , salary: 50000, details: function () { return "Employee Name: " + this .ename + "-->Salary: " + this .salary; } } let deepCopy = lodash.cloneDeep(employee); console.log( "Original Employee Object" ); console.log(employee); console.log( "Deep Copied Employee Object" ); console.log(deepCopy); deepCopy.eid = "E103" ; deepCopy.ename = "Beck" ; deepCopy.details = function () { return "Employee ID: " + this .eid + "-->Salary: " + this .salary; } console.log( "----------After Modification----------" ); console.log( "Original Employee Object" ); console.log(employee); console.log( "Deep Copied Employee Object" ); console.log(deepCopy); console.log(employee.details()); console.log(deepCopy.details()); |
Output:
Explanation: Both objects have different properties after the modification. Also, the methods of each object are differently defined and produce different outputs.
The better way to deepcopy in javascript: https://www.w3wiki.org/how-to-deep-clone-in-javascript/
What is shallow copy and deep copy in JavaScript ?
JavaScript is a high-level, dynamically typed client-side scripting language. JavaScript adds functionality to static HTML pages. Like most other programming languages JavaScript allows supports the concept of deep copy and shallow copy.