Site icon Teaching Newbies since 2014

Deep & shallow copying in JavaScript – part 3

Copying objects with deep copy

The JSON.stringify and JSON.parse methods can be used to deep copy an object.
In a deep copy, the source and target objects have different memory addresses and are not connected at all. The JSON.stringify() method will take a JavaScript object as an
argument and transform it into a string. Then the JSON.parse() method will parse the
JavaScript string and return a JavaScript object. For example take an object called object1 which has a nested object called division:

let object1 = {
role: 'HR',
division: {
management: 'HR Recruiter',
},
}

The object is first transformed into a string and then this string will be parsed and converted into an object before being returned:

let object2 = JSON.parse(JSON.stringify(object1));
console.log(object2);

object2 now has the role property including the nested management property copied over to it:

[object Object] {
division: [object Object] {
management: "HR Recruiter"
},
role: "HR"
}

Let’s change the value of the management property in the deep clone object2:

object2.division.management = 'dev';

object2 now has the following property : value pairs:

Object {
division: Object {
management: "dev"
},
role: "HR"
}

We have changed the value of a reference type (object) in object2. Do you think that this
change will be reflected in object1? Let’s check:

console.log(object1);

It is observed that the object1 object has no changes to it:

Object {
division: Object {
management: "HR Recruiter"
},
role: "HR"
}

This is because, in a deep copy, the source and target objects have different memory
addresses and are not connected at all. Therefore, changing any of the values (primitive or object) in the source or target objects after making a deep clone using the
JSON.stringify() and JSON.parse() methods will have no effect.

Note

This method has the drawback that the Date, RegExp objects, and Infinity cannot be used.
Only deeply nested values containing strings, numbers, booleans, and the null data type can be used. In order to clone nested objects, the Date object and other values used a custom function to iterate . For example:

function cloneObject(obj) {
    let clone = {};
    for (let i in obj) {
        if (obj[i] != null && typeof(obj[i]) ===
            "object")
            clone[i] = cloneObject(obj[i]);
        else
            clone[i] = obj[i];
    }
    return clone;
}
Exit mobile version