JSON深度合并

实现

对值进行分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getObjectType(object) {
if (object === undefined) {
return "undefined";
}
if (object === null) {
return "null";
}
if (typeof object !== "object") {
return "unit";
}
if (object instanceof Array) {
return "array";
}
return "object";
}

arrayobject的值进行递归合并

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
function deepMergeObject(...objects) {
let subs = [];
for (let obj of objects) {
if (obj === undefined) {
continue;
}
if (subs.length > 0 && getObjectType(obj) !== getObjectType(subs[0])) {
subs = [obj];
} else {
subs.push(obj);
}
}
if (subs.length === 0) {
return undefined;
}
let type = getObjectType(subs[0]);
if (subs.length === 1 || (type !== "object" && type !== "array")) {
return subs[subs.length - 1];
}
let keySet = new Set();
for (let obj of objects) {
for (let k in obj) {
keySet.add(k);
}
}
let newObj = type === "object" ? {} : [];
for (let k of keySet) {
let child = [];
for (let obj of subs) {
child.push(obj[k]);
}
newObj[k] = deepMergeObject(...child);
}
return newObj;
}

说明

数据分为undefinednullunitobjectarray,
deepMergeObject(a,b,c,d)调用过程中, 不同类型后者覆盖前者,
忽略undefined, objectarray进行keyindex遍历对子值进行递归合并

 欢迎关注我的博客公众号
如果觉得我的文章对你有用,请随意赞赏
0%