How to perform a deep copy of an object in JavaScript

Posted by

How to do deep copy of an object in Javascript

How to do deep copy of an object in Javascript

Deep copying an object in Javascript can be a bit tricky, as simply copying an object using the assignment operator or Object.assign() only creates a shallow copy, meaning that nested objects or arrays within the original object will still be referenced and not duplicated. Here’s how you can do a deep copy of an object in Javascript:

Using JSON

One way to deep copy an object in Javascript is to use JSON.stringify() and JSON.parse(). Here’s an example:

    
    let originalObject = {
        name: 'John',
        age: 30,
        address: {
            street: '123 Main St',
            city: 'New York'
        }
    };

    let deepCopy = JSON.parse(JSON.stringify(originalObject));
    
    

In this example, JSON.stringify() takes the original object and converts it to a JSON string, and then JSON.parse() parses the JSON string back into a new object, effectively creating a deep copy of the original object.

Using a Recursive Function

Another approach to deep copy an object in Javascript is to use a recursive function. Here’s an example of how this can be done:

    
    function deepCopy(obj) {
        let result = Array.isArray(obj) ? [] : {};

        for (let key in obj) {
            if (typeof obj[key] === 'object' && obj[key] !== null) {
                result[key] = deepCopy(obj[key]);
            } else {
                result[key] = obj[key];
            }
        }

        return result;
    }

    let originalObject = {
        name: 'John',
        age: 30,
        address: {
            street: '123 Main St',
            city: 'New York'
        }
    };

    let deepCopy = deepCopy(originalObject);
    
    

In this example, the deepCopy() function recursively copies each property of the original object into a new object, effectively creating a deep copy.

These are just a couple of ways to deep copy an object in Javascript. Depending on your specific use case, one method may be more suitable than the other. It’s important to be aware of the differences between shallow and deep copies, and to choose the appropriate method to ensure that you’re creating an accurate copy of your original object.