Deep Clone Efficiently
A colleague recently pointed out to me that my use of lodash’s cloneDeep command was inefficient and unnecessary. More specifically, he said that if that’s the only reason I’m including lodash, or if it’s because of other simple things that can be solved with native JavaScript, I should reconsider the need to include a 70kb library to my projects if I didn’t need to.
It was suggested that I used JSON.stringify()
to turn the variable into a string instead, and then JSON.parse()
, to convert it back into a new object. This works, and I’d seen it before—even used it—but I hadn’t seen it as a viable solution for some reason.
My initial response, therefore, was, “But does JSON stringify and parse convert methods of an object?”
Short answer… it doesn’t. But on reflection, I’ve never needed that anyway.
My use for _.cloneDeep
by lodash was when working in React (specifically WordPress). I’d often need to take a multi-level object, duplicate it, and then change part of it so I could pass it back to the setAttributes function (setState if using standard React).
After my initial struggles with spread syntax, I moved to cloneDeep and used a bazooka to kill a rabbit.
I wrote functions like this:
deleteNode = (node) => {
let nodes = _.cloneDeep(this.props.attributes.nodes);
removeNodeWithId(nodes, node.id);
this.props.setAttributes({ nodes });
};
These work fine and solve the problem, but the second line can be done in vanilla JavaScript instead and (I’m told) is more efficient.
deleteNode = (node) => {
let nodes = JSON.parse( JSON.stringify(this.props.attributes.nodes) );
removeNodeWithId(nodes, node.id);
this.props.setAttributes({ nodes });
};
Notice how the second line above stringifies the object first, and then that is wrapped in a parse function to convert it back into a new object.
This works perfectly fine, and if you don’t like the readability of wrapping functions in functions unnecessarily, you can create another function like below.
Function deepClone(obj) => {
Return JSON.parse( JSON.stringify(obj) );
}
That’s it!
Thanks…
I also dissect and speculate on design and development.
Digging into subtle details and implications, and exploring broad perspectives and potential paradigm shifts.
Check out my conceptual articles on Substack or find my latest below.
You can also find me on Threads, Bluesky, Mastodon, or X for more diverse posts about ongoing projects.
Leave a Reply