deepMerge.js 1.0 KB

1234567891011121314151617181920212223242526272829
  1. import deepClone from "./deepClone";
  2. // JS对象深度合并
  3. function deepMerge(target = {}, source = {}) {
  4. target = deepClone(target);
  5. if (typeof target !== 'object' || target === null || typeof source !== 'object' || source === null) return target;
  6. const merged = Array.isArray(target) ? target.slice() : Object.assign({}, target);
  7. for (const prop in source) {
  8. if (!source.hasOwnProperty(prop)) continue;
  9. const sourceValue = source[prop];
  10. const targetValue = merged[prop];
  11. if (sourceValue instanceof Date) {
  12. merged[prop] = new Date(sourceValue);
  13. } else if (sourceValue instanceof RegExp) {
  14. merged[prop] = new RegExp(sourceValue);
  15. } else if (sourceValue instanceof Map) {
  16. merged[prop] = new Map(sourceValue);
  17. } else if (sourceValue instanceof Set) {
  18. merged[prop] = new Set(sourceValue);
  19. } else if (typeof sourceValue === 'object' && sourceValue !== null) {
  20. merged[prop] = deepMerge(targetValue, sourceValue);
  21. } else {
  22. merged[prop] = sourceValue;
  23. }
  24. }
  25. return merged;
  26. }
  27. export default deepMerge;