You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
29 lines
1.0 KiB
29 lines
1.0 KiB
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;
|
|
|