How to Deep Clone an Object Using JavaScript ?
You can use Lodash library to deep clone an object.
Start by importing the library.
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Once you have the library, you can use cloneDeep
method to clone the original object.
let originalObj = {
keys: [1, 2, 3],
empInfo: {
firstName: 'jay',
lastName: 'raj',
age: 10
}
};
let clonedObj = _.cloneDeep(originalObj);
clonedObj.empInfo = null;
console.log('Original object is ', originalObj);
console.log('Cloned obj is ', clonedObj);
//- "Original object is ",
// { empInfo:
// { age: 10, firstName: "jay", lastName: "raj" }, keys: [1, 2, 3] }
// "Cloned obj is ",
// { empInfo: null, keys: [1, 2, 3] }