DEV Community

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

Posted on

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

Top comments (0)