Skip to content

JavaScript deep copy object | Example code

  • by

Use JSON.stringify() and JSON.parse() methods to deep copy objects in JavaScript. The JSON.stringify() method takes in an object and creates a JSON string from it. The JSON.parse() method parses a string and returns a JavaScript object.

No such functionality is built in into ES6. I think you have a couple of options depending on what you want to do.

If you really want to deep copy:

  1. Use a library. For example, lodash has a cloneDeep method.
  2. Implement your own cloning function.

JavaScript deep copy object

Simple example code simple object with no methods, one quick way is to serialize the object and then parse it again.

<!DOCTYPE html>
<html>
<body>

  <script>
    const Obj = {
      id: 1,
      version: 1,
      person: 'jack'
    };

    const copy = JSON.parse(JSON.stringify(Obj));

    Obj.person = "changed this";

    console.log(copy);
    console.log(Obj);

  </script>

</body>
</html> 

Output:

JavaScript deep copy object

5 Ways to Deep Copy Objects in JavaScript

Deep copy in ES6 using the spread syntax

MethodProsCons
shallow copy with =clear and direct, the defaultonly shallow copies objects
JSON.stringify() and JSON.parse()only shallow copies of objectsdoesn’t copy functions
Object.assign()copies the immediate members of an object—including functionsdoesn’t deep copy nested objects
the ... spread operatorsimple syntax, the preferred way to copy an objectdoesn’t deep copy nested objects
Lodash cloneDeep()clones nested objects including functionsadds an external dependency to your project

How to deep copy a custom object in JavaScript?

Answer: Use Object.assign, which “is used to copy the values of all enumerable own properties from one or more source objects to a target object”.

const obj1 = {a:1, b:2};
const obj1Copy = Object.assign(obj1)

Alternatively, you can use the spread operator to spread from one object into another. Keep in mind that this will copy the values of keys, but if the value of a key is a memory address (another nested object or an array) then it will only be a shallow copy.

const obj1 = {a: () => {}, b:2}
const obj1Copy = { ...obj1 }

If the object doesn’t have any circular references or functions as values, you can use the json stringify trick:

let myCopy = JSON.parse(JSON.stringify(myObject));

Source: stackoverflow.com

Comment if you have any doubts or suggestions on this JS copy 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

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