cloneDeep In Lodash (Javascript Library)
Hey!, Since I started working on VueJs I have been learning new things from a big codebase. I hope I'll continue to share my learnings over here....
Hey!, Since I started working on VueJs I have been learning new things from a big codebase. I hope I'll continue to share my learnings over here.
Have you ever tried to copy an object in JavaScript and discovered that changing the copy also changes the original? That’s because you made a shallow copy. Sometimes, you need a deep copy, and that's where cloneDeep
from Lodash comes in handy
What is cloneDeep?
In short, cloneDeep
is a function from Lodash, a cool JavaScript library, that allows you to copy objects without affecting the original state.
Why Do We Need cloneDeep
?
If you only make a shallow copy, the inner objects still point to the same place in memory. So, changes to the copy will affect the original. Deep copying avoids this problem.
Shallow Copy (as mentioned below in the code snippet)
const original = { a: 1, b: { c: 2 } };
const shallowCopy = { ...original };
shallowCopy.b.c = 3;
console.log(original.b.c); // Output: 3
Deep Copy (as mentioned below in the code snippet)
const original = { a: 1, b: { c: 2 } };
const deepCopy = _.cloneDeep(original);
deepCopy.b.c = 3;
console.log(original.b.c); // Output: 2
console.log(deepCopy.b.c); // Output: 3
How to Use cloneDeep
First, install Lodash using npm or yarn:
npm install lodash
or
yarn add lodash
Usage
import _ from 'lodash';
const original = { a: 1, b: { c: 2 } };
const deepCopy = _.cloneDeep(original);
deepCopy.b.c = 3;
console.log(original.b.c); // Output: 2
console.log(deepCopy.b.c); // Output: 3
Things to Watch Out For
Conclusion
cloneDeep
is a lifesaver when you need a full, independent copy of an object in JavaScript. It’s easy to use and helps avoid many headaches with state management and data manipulation. Happy Coding! 😉