mergeDeep.ts28 lines · main
| 1 | /** |
| 2 | * Check if item is Object |
| 3 | */ |
| 4 | export function isObject(item: any): boolean { |
| 5 | return item && typeof item === 'object' && !Array.isArray(item) |
| 6 | } |
| 7 | |
| 8 | /** |
| 9 | * Deep merge two objects. |
| 10 | * @return merged object |
| 11 | */ |
| 12 | export function mergeDeep(target: any, ...sources: any[]): any { |
| 13 | if (sources.length === 0) return target |
| 14 | const source = sources.shift() |
| 15 | |
| 16 | if (isObject(target) && isObject(source)) { |
| 17 | for (const key in source) { |
| 18 | if (isObject(source[key])) { |
| 19 | if (!target[key]) Object.assign(target, { [key]: {} }) |
| 20 | mergeDeep(target[key], source[key]) |
| 21 | } else { |
| 22 | Object.assign(target, { [key]: source[key] }) |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | return mergeDeep(target, ...sources) |
| 28 | } |