DEV Community

Cover image for Deep cloning of an object in JavaScript...
Nitin Reddy
Nitin Reddy

Posted on

1

Deep cloning of an object in JavaScript...

As JavaScript developers, we most often than not come across a situation where we want to clone an object and reuse it to perform some operations.

And we usually follow well-known approaches to deep clone the object:-

  • lodash's cloneDeep method
  • JSON.parse(JSON.stringify(object))

What if I say that you are not supposed to use the above two approaches and you should create your custom method to deep clone the object?

I have an answer for that. Let's write a utility method that would help us in achieving the deep cloning of an object.

Example

Let us say that I have a nested object as below

let emptyStack = {
  feTools: 'JS, React, NextJS, Tailwindcss, Netlify',
  react: {
    baseConcepts: 'props, states, hooks',
    advancedConcepts: {
      hoc: 'composition of the functions',
      contextApi: 'Sharing the data without prop drilling'
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

So in the above, as you can see we have the nested objects inside emptyStack. Let us try to understand and evaluate what all steps are required to be executed to achieve the deep cloning of an object.

Pseudo code

Steps:

  1. Initialize a new empty object
  2. Iterate over the keys of an object and check if the key-value pair is an object
  3. And based on the result of Step#2 update the empty object with the new properties.
  4. Repeat the Step#2 and #3 till the last element of an object is evaluated.

The ultimate utility method

function deepCopy(currentObj) {
  let newObj = Array.isArray(currentObj) ? [] : {}; //Step#1
  for (let key in currentObj) { //Step#2
    let property = currentObj[key];
    if (typeof property === "object") {
      newObj[key] = deepCopy(property); //Step#3
    } else {
      newObj[key] = property; //Step#3
    }
  }
  return newObj;
}
Enter fullscreen mode Exit fullscreen mode

Usage

let deepClonedObject = deepCopy(emptyStack)

console.log(`${JSON.stringify(deepClonedObject)}`)
/** Output
{"feTools":"JS, React, NextJS, Tailwindcss, Netlify","react":{"baseConcepts":"props, states, hooks","advancedConcepts":{"hoc":"composition of the functions","contextApi":"Sharing the data without prop drilling"}}} */
Enter fullscreen mode Exit fullscreen mode

What all concepts are used in the above method?

  • Recursive function
  • Object keys iteration

Recursive function

Conclusion

Deep cloning an object is really useful in the scenarios where you want the back referencing to happen for a cloned object.
There are more posts on the way related to the lists...So keep reading.

Thanks in advance for reading this article...🚀

I am more than happy to connect with you on

You can also find me on

Postmark Image

20% off for developers who'd rather build features than debug email

Stop wrestling with email delivery and get back to the code you love. Postmark handles the complexities of email infrastructure so you can ship your product faster.

Start free

Top comments (0)

Postmark Image

"Please fix this..."

Focus on creating stellar experiences without email headaches. Postmark's reliable API and detailed analytics make your transactional emails as polished as your product.

Start free

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. ❤️