Skip to content

Instantly share code, notes, and snippets.

@pbakondy
Forked from dysfunc/angular-deep-extend.js
Last active February 11, 2016 11:33
Show Gist options
  • Save pbakondy/2462e3ba5fbcf50379ec to your computer and use it in GitHub Desktop.
Save pbakondy/2462e3ba5fbcf50379ec to your computer and use it in GitHub Desktop.
/*
* Note: this code is for Angular.js v1.3 or earlier
* In Angular.js v1.4+ you can use angular.merge()
*
* Extends the destination object `dst` by copying all of the properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects.
* @param {Boolean} deep If true, the merge becomes recursive (optional aka deep copy)
* @param {Object} dst Destination object.
* @param {Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*
* angular.extend(object, object2) // shallow copy
* angular.extend(true, object, object2) // deep copy
*
* It acceps only Objects as source, everything else will be ignored
*/
angular.extend = function(dst){
var deep = false,
i = 1,
arglist;
if(typeof(dst) === 'boolean'){
deep = dst;
dst = arguments[1] || {};
i++;
}
arglist = [].slice.call(arguments, i).filter(function(n) {
return angular.isObject(n);
});
angular.forEach(arglist, function(obj){
var array, clone, copy, key, src;
for(key in obj){
src = dst[key];
copy = obj[key];
if(dst === copy){
continue;
}
if(deep && copy && (angular.isObject(copy) ||
(array = angular.isArray(copy)))){
if(array){
clone = (src && angular.isArray(src)) ? src : [];
}else{
clone = (src && angular.isObject(src)) ? src : {};
}
dst[key] = angular.extend(deep, clone, copy);
}
else if(copy !== undefined){
dst[key] = copy;
}
}
});
return dst;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment