5

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
James Madison
  • 337
  • 1
  • 4
  • 17
  • Could you add the code where orig and companyData are defined? – Chitrang Aug 27 '15 at 21:00
  • @Chitrang added it now – James Madison Aug 27 '15 at 21:06
  • 1
    Seems to be working as expected... https://jsfiddle.net/ufm3vyvL/ – Andrea Casaccia Aug 27 '15 at 21:08
  • 1
    Your code works: http://jsfiddle.net/8fsce0yq/ – Jack Aug 27 '15 at 21:08
  • 1
    Your code given is already working as you expect. jQuery deep copy should work unless you are creating orig or companyData variable some other way like "new MyCustomObject(args)". – Chitrang Aug 27 '15 at 21:18
  • @Chitrang hmm, I see that it works in the fiddle but I just did more checks, it isn't working in my project still. when the companyData is populated it's companyData = $.parseJSON(jsonData); I don't see how this would be any different though... once it's parsed it's just an object just like other js object – James Madison Aug 27 '15 at 21:33
  • 1
    [I cannot reproduce](https://fiddle.jshell.net/zeqa5ucj/). It does log 1, 0, 1 as expected. – Bergi Aug 27 '15 at 21:46
  • 1
    @JamesMadison: Please post your actual code and same short sample JSON – Bergi Aug 27 '15 at 21:47

2 Answers2

0

You must pass both objects to be combined

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

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

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

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

See this code running

Carlos Laspina
  • 2,013
  • 4
  • 27
  • 44
0

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));
};
James Madison
  • 337
  • 1
  • 4
  • 17