merge.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. var hasOwn = require('./hasOwn');
  2. var deepClone = require('../lang/deepClone');
  3. var isObject = require('../lang/isObject');
  4. /**
  5. * Deep merge objects.
  6. */
  7. function merge() {
  8. var i = 1,
  9. key, val, obj, target;
  10. // make sure we don't modify source element and it's properties
  11. // objects are passed by reference
  12. target = deepClone( arguments[0] );
  13. while (obj = arguments[i++]) {
  14. for (key in obj) {
  15. if ( ! hasOwn(obj, key) ) {
  16. continue;
  17. }
  18. val = obj[key];
  19. if ( isObject(val) && isObject(target[key]) ){
  20. // inception, deep merge objects
  21. target[key] = merge(target[key], val);
  22. } else {
  23. // make sure arrays, regexp, date, objects are cloned
  24. target[key] = deepClone(val);
  25. }
  26. }
  27. }
  28. return target;
  29. }
  30. module.exports = merge;