Search code examples
javascriptjqueryclonedeep-copycloneable

jQuery deep clone isn't recursive


I am using js/jQuery and am attempting to create a true clone- I'm currently using jQuery for this. I would expect that in multi-level objects even the child objects should be deep cloned, but this appears to not be the case. Below is my test code and out put that leads me to believe that jQuery's deep clone doesn't actually clone all the child objects.

has anyone written a true deep clone function, or is there a way of making jQuery's work as expected?

Code:

function deepClone (obj) {
    return $.extend(true, {}, obj);
};

var orig = {};
orig.companyData = {};
orig.companyData.TEST= 1;

var deep1 = deepClone(orig);
deep1.companyData.TEST= 0;

var deep2 = deepClone(orig);

console.log("orig: " + orig.companyData.TEST);
console.log("deep1: " + deep1.companyData.TEST);
console.log("deep2: " + deep2.companyData.TEST);

Console Output:

Note: I expect 1, 0, 1

0 
0
0

Solution

  • jQuery's extend function seems to work on most objects, some users have suggested that the issue may be with the way that my js object was created- I'm not sure what the culprit is, but my solution is below:

    function deepClone(obj) {
        return $.parseJSON(JSON.stringify(obj));
    };