DeepCopy not copying objects


#1

I’m using deepCopy() from dojo/request/util to try to make a copy of an object that’s independent of the original object. To do this I’m using the format
var newOjb = util.deepCopy({}, oldObj);
When I do this, it looks like newObj is getting references to objects in oldObj rather than creating a new object for newObj. Is this how deepCopy was intended to work, or should it be making a copy of all the child objects?

If the child objects should be getting copied, I’ve modified the deepCopy function and put examples of it in: https://plnkr.co/edit/WT4iXQITW0F5vfFNZwuU?p=preview This shows what happens to an object when you create it, copy/clone it, and then modify the original.

Thanks for the help.

Nathan


#2

I made another update to the deepCopy() function to handle arrays. I think this deepCopy function is working with child objects and arrays now:

function deepCopy(target, source, i) {
  	  i = i || 0;
  		console.log(i + ". deepCopy(" + JSON.stringify(target) + ", " + JSON.stringify(source));
  		for (var name in source) {
  			var tval = target[name], 
  			    sval = source[name];
  			if (tval !== sval) {
  				if (sval && typeof sval === 'object') {
  					console.log(i + ". source is an object: " + JSON.stringify(sval));
  					if (Object.prototype.toString.call(sval) === '[object Date]') { // use this date test to handle crossing frame boundaries
  						target[name] = new Date(sval);
  					} else if (Array.isArray(sval)) {
   						  console.log(i + ". source is array: " + JSON.stringify(sval));
   						  target[name] = deepCopyArray(sval);
  					} else {
  						if (tval && typeof tval === 'object') {
  						  console.log(i + ". target is object: " + JSON.stringify(tval));
  							deepCopy(tval, sval, i++);
  						} else {
  						  console.log(i + ". target is NOT object: " + JSON.stringify(tval));
  							target[name] = deepCopy({}, sval, i++);
  						}
  					}
  				} else {
  					console.log(i + ". source is NOT object: " + JSON.stringify(sval));
  					target[name] = sval;
  				}
  			}
  		}
  		console.log(i + ". returning: " + JSON.stringify(target));
  		return target;
  	}
  	
  	function deepCopyArray(source) {
  console.log("deepCopyArray(" + JSON.stringify(source) + ")");
  var clonedArray = [];
 	    source.forEach(function(svalItem) {
 	      if (typeof svalItem === 'object') {
 	        clonedArray.push(deepCopy({}, svalItem));
 	      } else {
 	        clonedArray.push(svalItem);
 	      }
 	    });
  console.log("deepCopyArray return: " + JSON.stringify(clonedArray));
 	    return clonedArray;
  	}

I have also updated the example at http://plnkr.co/edit/Ee3zqUemvKfFVqI3mo73 Should this be updated in dojo/request/util?


#3

Probably… care to open a pull request for review?