通过递归合并JSON:
function mergeJSON(o, n) {
let oType = Object.prototype.toString.call(o);
let nType = Object.prototype.toString.call(n);
if (nType == '[object Object]' && oType == '[object Object]') {
//合并属性(object)
for (let p in n) {
if (n.hasOwnProperty(p) && !o.hasOwnProperty(p)) {
o[p] = n[p];
} else if (n.hasOwnProperty(p) && (o.hasOwnProperty(p))) {
let oPType = Object.prototype.toString.call(o[p]);
let nPType = Object.prototype.toString.call(n[p]);
if ((nPType == '[object Object]' && oPType == '[object Object]') || (nPType == '[object Array]' && oPType == '[object Array]')) {
mergeJSON(o[p], n[p]);
} else {
o[p] = n[p];
}
}
}
} else if (nType == '[object Array]' && oType == '[object Array]') {
//合并属性(array)
for (let i in n) {
let oIType = Object.prototype.toString.call(o[i]);
let nIType = Object.prototype.toString.call(n[i]);
if ((nIType == '[object Object]' && oIType == '[object Object]') || (nIType == '[object Array]' && oIType == '[object Array]')) {
mergeJSON(o[i], n[i]);
} else {
o[i] = n[i];
}
}
}
//合并属性(other)
o = n;
}
//test
let json1={
"a": "json1",
"b": 123,
"c": {
"dd": "json1 dd",
"ee": 556,
"f": "ff1"
},
"list": [
{
"a": 123,
"b": 96
},
{
"a": 45,
"b": 56
}
]
};
let json2={
"a": "json2",
"a2": 369,
"c": {
"dd2": "json2 dd",
"ee": "gg2"
},
"list": [
{
"a": "a1",
"b1": 69
},
369,
{
"i3": 36
}
]
};
mergeJSON(json1,json2);
console.log(JSON.stringify(json1));