在JavaScript中,深度合并JSON对象是指将两个或多个JSON对象合并成一个新对象,并且如果这些对象中有嵌套的对象或数组,也要进行递归合并,而不是简单的覆盖。
以下是一个使用递归实现深度合并的函数:
function isObject(obj) {
return obj && typeof obj === 'object' && !Array.isArray(obj);
}
function deepMerge(target, ...sources) {
if (!sources.length) return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
deepMerge(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return deepMerge(target, ...sources);
}
// 使用示例
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 3 }, e: 4 };
const mergedObj = deepMerge({}, obj1, obj2);
console.log(mergedObj); // 输出: { a: 1, b: { c: 2, d: 3 }, e: 4 }
function deepMerge(target, ...sources) {
const visited = new WeakSet();
function merge(target, source) {
if (isObject(target) && isObject(source)) {
if (visited.has(target) || visited.has(source)) {
return; // 避免循环引用
}
visited.add(target);
visited.add(source);
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
merge(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
}
sources.forEach(source => merge(target, source));
return target;
}
通过这种方式,可以实现一个更加健壮的深度合并函数,能够处理更复杂的情况。
领取专属 10元无门槛券
手把手带您无忧上云