Skip to content

Deep clone object JavaScript | Example code

  • by

Use JSON parse and stringify method to do deep clone object JavaScript. If the object doesn’t have any circular references or functions as values, you can use the json stringify trick:

JSON.parse(JSON.stringify(object))

Deep clone object JavaScript

Simple example code fast cloning with data loss – JSON.parse/stringify.

<!DOCTYPE html>
<html>
<body>
  <script>
    const a = {
      string: 'string',
      number: 123,
      bool: false,
      nul: null,
      date: new Date(),  // stringified
      undef: undefined,  // lost
      inf: Infinity,  // forced to 'null'
      re: /.*/,  // lost
    }
    console.log(a);
    console.log(typeof a.date);  // Date object

    const clone = JSON.parse(JSON.stringify(a));
    
    console.log(clone);
    console.log(typeof clone.date);
</script>
</body>
</html> 

Output:

Deep clone object JavaScript

Native deep cloning

There’s now a JS standard called “structured cloning”, which works experimentally in Node 11 and later, will land in browsers, and which has polyfills for existing systems.

structuredClone(value)

If needed, load the polyfill first:

import structuredClone from '@ungap/structured-clone';

How to deep copy a custom object in JavaScript?

Answer: You can use lodash’s cloneDeep function – https://lodash.com/docs/4.16.4#cloneDeep

Example (from docs)

var objects = [{ 'a': 1 }, { 'b': 2 }];

var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false

Source: https://stackoverflow.com

Using a recursive function: This method allows for deep cloning of objects with circular references and non-JSON serializable values.

function deepClone(obj, visited = new WeakMap()) {
  // Check if the object has already been visited and cloned
  if (visited.has(obj)) {
    return visited.get(obj);
  }

  // Handle non-object types
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  // Create a new object or array for the cloned object
  const clone = Array.isArray(obj) ? [] : {};

  // Store the cloned object in the visited map
  visited.set(obj, clone);

  // Recursively clone nested objects and arrays
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clone[key] = deepClone(obj[key], visited);
    }
  }

  return clone;
}

const originalObj = { a: 1, b: { c: 2 } };
const clonedObj = deepClone(originalObj);

However, it may be slower and consume more memory for deeply nested objects. Choose the method that best suits your specific use case.

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading