Commit 4c63b1abb7df9ed5330dc196555a924926fcf684

Authored by Kirk Lin
Committed by GitHub
1 parent 5d8d9786

refactor: deepMerge (#2649)

Showing 1 changed file with 21 additions and 10 deletions
src/utils/index.ts
@@ -2,8 +2,8 @@ import type { RouteLocationNormalized, RouteRecordNormalized } from 'vue-router' @@ -2,8 +2,8 @@ import type { RouteLocationNormalized, RouteRecordNormalized } from 'vue-router'
2 import type { App, Component } from 'vue'; 2 import type { App, Component } from 'vue';
3 3
4 import { unref } from 'vue'; 4 import { unref } from 'vue';
5 -import { isObject } from '/@/utils/is';  
6 -import { cloneDeep } from 'lodash-es'; 5 +import { isArray, isObject } from '/@/utils/is';
  6 +import { cloneDeep, mergeWith } from 'lodash-es';
7 7
8 export const noop = () => {}; 8 export const noop = () => {};
9 9
@@ -33,14 +33,25 @@ export function setObjToUrlParams(baseUrl: string, obj: any): string { @@ -33,14 +33,25 @@ export function setObjToUrlParams(baseUrl: string, obj: any): string {
33 return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, '?') + parameters; 33 return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, '?') + parameters;
34 } 34 }
35 35
36 -// 深度合并  
37 -export function deepMerge<T = any>(src: any = {}, target: any = {}): T {  
38 - let key: string;  
39 - const res: any = cloneDeep(src);  
40 - for (key in target) {  
41 - res[key] = isObject(res[key]) ? deepMerge(res[key], target[key]) : target[key];  
42 - }  
43 - return res; 36 +/**
  37 +
  38 + 递归合并两个对象。
  39 + Recursively merge two objects.
  40 + @param target 目标对象,合并后结果存放于此。The target object to merge into.
  41 + @param source 要合并的源对象。The source object to merge from.
  42 + @returns 合并后的对象。The merged object.
  43 + */
  44 +export function deepMerge<T extends object | null | undefined, U extends object | null | undefined>(
  45 + target: T,
  46 + source: U,
  47 +): T & U {
  48 + return mergeWith(cloneDeep(target), source, (objValue, srcValue) => {
  49 + if (isObject(objValue) && isObject(srcValue)) {
  50 + return mergeWith(cloneDeep(objValue), srcValue, (prevValue, nextValue) => {
  51 + return isArray(prevValue) ? prevValue.concat(nextValue) : undefined;
  52 + });
  53 + }
  54 + });
44 } 55 }
45 56
46 export function openWindow( 57 export function openWindow(