For those not using jQuery, here comes the vanilla-js solution.
Decision
function extend (target) { for(var i=1; i<arguments.length; ++i) { var from = arguments[i]; if(typeof from !== 'object') continue; for(var j in from) { if(from.hasOwnProperty(j)) { target[j] = typeof from[j]==='object' ? extend({}, target[j], from[j]) : from[j]; } } } return target; }
Compressed (with Closure Compiler ):
Only 199 characters!
var extend=function e(c){for(var d=1;d<arguments.length;++d){var a=arguments[d];if("object"===typeof a)for(var b in a)a.hasOwnProperty(b)&&(c[b]="object"===typeof a[b]?e({},c[b],a[b]):a[b])}return c}
How to use :
extend(target, obj1, obj2);
If you want to combine, use
var merged = extend({}, obj1, obj2);
Functions
- He does not look at prototype objects.
- Ignores no objects.
- It is recursive to combine properties that are objects.
- Objects referenced by the
target properties, if extended, are replaced with new ones, but the original ones are not changed. - In the case of identical property names, the combined value will be the union of the objects after the last (in the order of arguments) value other than the object. Or, if the latter is not an object, itself.
<strong> Examples:
extend({}, {a:1}, {a:2});
Attention
Remember that if the browser is not smart enough, it can be captured in an endless loop:
var obj1={}, obj2={}; obj1.me=obj1; obj2.me=obj2; extend({},obj1,obj2);
If the browser is smart enough, it may throw an error or return {me: undefined} or something else.
Note that this warning also applies if you are using jQuery $.extend .