onsa
12/16/2016 - 11:18 PM

Update the properties of an object from another source object but leave unmatched properties alone.

Update the properties of an object from another source object but leave unmatched properties alone.

var updateObject = function(sourceObject, targetObject) {
	for (var key in sourceObject) {
		if (sourceObject.hasOwnProperty(key)) { //  skip prototype properties
			if (typeof key === 'object' && targetObject.hasOwnProperty(key)) {  //  if property is an object itself AND target already has such property
				updateObject(sourceObject[key], targetObject[key]); //  run recursively on property
			} else {
				targetObject[key] = sourceObject[key];  //  otherwise it's safe simply to copy property
			}
		}
	}
};