知食记
搜索文档…
实现 merge
1
/**
2
* Simple is object check.
3
* @param item
4
* @returns {boolean}
5
*/
6
function isObject(item) {
7
return (item && typeof item === 'object' && !Array.isArray(item) && item !== null);
8
}
9
10
11
/**
12
* Deep merge two objects.
13
* @param target
14
* @param source
15
*/
16
export function mergeDeep(target, source) {
17
if (isObject(target) && isObject(source)) {
18
Object.keys(source).forEach(key => {
19
if (isObject(source[key])) {
20
if (!target[key] || !isObject(target[key])) {
21
target[key] = source[key];
22
}
23
mergeDeep(target[key], source[key]);
24
} else {
25
Object.assign(target, { [key]: source[key] });
26
}
27
});
28
}
29
return target;
30
}
31
32
const A={
33
var_a: {
34
'loc': 'Earth',
35
'title': 'Hello World',
36
'type': 'Planet',
37
'deeper':{
38
'map':new Map([['a', 'AAA'],['b', 'BBB']]),
39
'mapId':15473,
40
}
41
}
42
};
43
44
const B={
45
var_a: {
46
'type': 'Star',
47
'deeper':{
48
'mapId':9999,
49
'alt_map':new Map([['x', 'XXXX'],['y', 'YYYY']]),
50
}
51
}
52
}
53
54
function assert(condition, message) {
55
if (!condition) {
56
message = message || "Assertion failed";
57
if (typeof Error !== "undefined") {
58
throw new Error(message);
59
}
60
throw message; // Fallback
61
}
62
}
63
64
const C = mergeDeep(A,B);
65
const D = mergeDeep({a: 1}, { b : { c: { d: { e: 12345}}}});
66
const E = mergeDeep({b: {c: 'hallo'}}, { b : { c: { d: { e: 12345}}}});
67
const F = mergeDeep({ b : { c: { d: { e: 12345}}, d:'dag', 'f':'one'}}, {b: {c: 'hallo', e:'ok',f:'two'}});
68
69
assert (C.var_a.type === "Star");
70
assert (C.var_a.deeper.alt_map.get('x') === 'XXXX');
71
assert (C.var_a.deeper.map.get('b') === 'BBB');
72
assert (D.a === 1);
73
assert (D.b.c.d.e === 12345);
74
assert (E.b.c.d.e === 12345);
75
assert (F.b.c === 'hallo');
76
assert (F.b.d === 'dag');
77
assert (F.b.e === 'ok')
78
assert (F.b.f === 'two')
Copied!
复制链接