Skip to content

Object assign deep copy JavaScript

  • by

The JavaScript Object assign() method only copies enumerable and own properties from a source object to a target object. Using Object.assign(), you are actually doing a Shallow Copy of your object.

Can perform a copy on objects using the following methods:

MethodProsCons
shallow copy with =clear and direct, the defaultonly shallow copies of objects
JSON.stringify() and JSON.parse()deep copies nested 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

Object assign deep copy JavaScript

Simple example code Object.assign only does a shallow copy of the keys and values, meaning if one of the values in the object is another object or an array, then it is the same reference as was on the original object.

<!DOCTYPE html>
<html>
<body>

  <script>
    var x = { a: 10, b: { c: 100 } };
    var y = Object.assign({}, x);

    y.a = 20;
    console.log( x.a, y.a ); 

    y.b.c = 200;
    console.log( x.b.c, y.b.c ) 

  </script>
</body>
</html>

Output:

Object assign deep copy JavaScript

To deep copy an object, you can use something like the cloneDeep function in lodash or take an uglier approach using built-in functions with JSON.parse( JSON.stringify( obj ) ).

Note: The second option will only work with primitive types that are supported by JSON.

Source: https://stackoverflow.com/

Do comment if you have any doubts or suggestions on this JS deep copy coding.

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 *