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 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/

To achieve a deep copy in JavaScript, you typically need to implement a custom function. Here’s one way to create a deep copy of an object:

function deepCopy(obj) {
    // Check if the passed value is an object
    if (typeof obj !== 'object' || obj === null) {
        return obj; // Return primitives and null as is
    }
    
    // Create an empty object/array with the same prototype of the original
    const copy = Array.isArray(obj) ? [] : {};
    
    // Iterate over the keys of the original object
    for (let key in obj) {
        // Check if the key is an own property of the object (not from prototype chain)
        if (obj.hasOwnProperty(key)) {
            // Recursively deep copy nested objects/arrays
            copy[key] = deepCopy(obj[key]);
        }
    }
    
    return copy;
}

// Example usage:
const original = {
    a: 1,
    b: {
        c: 2,
        d: [3, 4]
    }
};

const copied = deepCopy(original);

console.log(copied); // { a: 1, b: { c: 2, d: [3, 4] } }

This deepCopy() function recursively copies nested objects and arrays, ensuring that the copied object is entirely independent of the original, even for nested structures.

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

Discover more from Tutorial

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

Continue reading