-
Notifications
You must be signed in to change notification settings - Fork 0
/
deep-merge.ts
46 lines (45 loc) · 975 Bytes
/
deep-merge.ts
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* @packageDocumentation
* @module @tomato-js/object
*/
import { ObjectType, isObject, isArray } from "@tomato-js/shared";
/**
* 对对象进行深层merge
*
* 新增于v0.0.24
*
* 脚本举例
* ```
* import { deepMerge } from '@tomato-js/object'
* deepMerge(
* a: { b:{ c: 'd' } },
* a: { b:{ e: 'f' } },
* a: { g: 'h' }
* );
* //{
* // a: {
* // b: {
* // c: 'd',
* // e: 'f'
* // }
* // g: 'h'
* // }
* //}
*
* ```
*/
export function deepMerge(...objects: ObjectType<any>[]) {
return objects.reduce((prev: ObjectType<any>, obj: ObjectType<any>) => {
for (const [key, oVal] of Object.entries(obj)) {
const pVal = prev[key];
if (isArray(pVal) && isArray(oVal)) {
prev[key] = pVal.concat(...oVal);
} else if (isObject(pVal) && isObject(oVal)) {
prev[key] = deepMerge(pVal, oVal);
} else {
prev[key] = oVal;
}
}
return prev;
}, {});
}