index.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * 对象浅拷贝
  3. * @param target 目标对象
  4. * @param source 源对象
  5. * @returns
  6. */
  7. export function merge<T>(target: T, ...source: T[]): T {
  8. source.forEach((e) => {
  9. for (const key in e) {
  10. if (Object.prototype.hasOwnProperty.call(target, key)) {
  11. target[key] = e[key];
  12. }
  13. }
  14. })
  15. return target;
  16. }
  17. /**
  18. * 对象深拷贝
  19. * @param target 目标对象
  20. * @param source 源对象
  21. * @returns
  22. */
  23. export function deepMerge<T>(target: T, source: T): T {
  24. for (const key in source) {
  25. // 判断属性是否存在
  26. if (Object.prototype.hasOwnProperty.call(target, key)) {
  27. const t = target[key];
  28. const s = source[key];
  29. // 对象属性类型检查
  30. switch (Object.prototype.toString.call(t)) {
  31. case '[object Object]':
  32. target[key] = deepMerge(t, s);
  33. break;
  34. case '[object Array]':
  35. if (Array.isArray(t) && Array.isArray(s)) {
  36. target[key] = t.reduce((prev, cur, i) => {
  37. const value = deepMerge(cur, s[i]);
  38. prev.push(value);
  39. return prev;
  40. }, [])
  41. }
  42. break;
  43. default:
  44. target[key] = s;
  45. }
  46. }
  47. }
  48. return target;
  49. }