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