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!

I’d love to know if any of these articles helped you.
Share what you’re building or ask me a question on Threads or somewhere else.

Instagram is a great place to see my final creative coding experiments, while the others are are great place to connect or see progress updates.

If my content has helped you, I’d never say no to donations to help me keep writing.

Here are some other things you might like


Author:

Date:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.