深度融合
递归融合,如果直接root.child = anotherObject.child ,原本root.child里面的内容会被完全替代,需要进行递归的每个同名项目的融合
class JsonMerge {
constructor() {
this.json = {};
}
add(obj) {
const data = JSON.parse(obj);
Object.keys(data).forEach((item) => {
if (this.json[item] === undefined) {
this.json[item] = JSON.parse(JSON.stringify(data[item]));
} else {
this.json[item] = this.deepMerge(this.json[item], data[item]);
}
});
}
get() {
return JSON.stringify(this.json, undefined, ' ');
}
deepMerge = (obj1, obj2) => {
Object.keys(obj2).forEach((key) => {
// eslint-disable-next-line no-param-reassign
obj1[key] = obj1[key] && obj1[key].toString() === '[object Object]' ? this.deepMerge(obj1[key], obj2[key]) : (obj1[key] = obj2[key]);
});
return obj1;
}
}
module.exports = JsonMerge;