Skip to content

Instantly share code, notes, and snippets.

@dysfunc
Last active March 2, 2017 01:30
Show Gist options
  • Save dysfunc/9701950 to your computer and use it in GitHub Desktop.
Save dysfunc/9701950 to your computer and use it in GitHub Desktop.
angular.extend - shallow + deep copy (supports merging of arrays and deduping)
/**
* Determine whether an Object is a plain object or not (created using "{}" or "new Object")
* @param {Object} obj Object we want to check
* @return {Boolean} True/False result
*/
angular.isPlainObject = function(obj){
return !(typeof(obj) !== 'object' || obj && obj.nodeType || obj !== null && obj === obj.window || obj && obj.constructor && !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf'));
};
/**
* Merge the contents of two or more objects into the target object
* @param {Boolean} deep If true, the merge becomes recursive (optional)
* @param {Object} target The object receiving the new properties
* @param {Object} arguments One or more additional objects to merge with the first
* @return {Object} The target object with the new contents
*
* angular.extend(object, object2) // shallow copy
* angular.extend(true, object, object2) // deep copy
*/
angular.extend = function(target){
var i = 1,
deep = false;
if(typeof(target) === 'boolean'){
deep = target;
target = arguments[1] || {};
i++;
}
angular.forEach([].slice.call(arguments, i), function(obj){
var src, copy, isArray, clone;
for(var key in obj){
src = target[key];
copy = obj[key];
if(target === copy){
continue;
}
if(deep && copy && (angular.isPlainObject(copy) || (isArray = copy instanceof Array))){
if(isArray){
clone = (src && src instanceof Array) ? src : [];
}else{
clone = (src && angular.isPlainObject(src)) ? src : {};
}
isArray = false;
target[key] = angular.extend(deep, clone, copy);
}
else if(copy !== undefined){
target[key] = copy;
}
}
});
return target;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment