JavaScript 合并对象与数组总结
一、合并对象
1. 浅拷贝合并
-
Object.assign()
const target = { a: 1 }; const source = { b: 2 }; const merged = Object.assign(target, source); // merged: { a: 1, b: 2 },target 被修改
- 特点:仅复制一层属性,嵌套对象仍为引用
- 注意:同名属性后覆盖前
-
展开语法(Spread Syntax)
const merged = { ...target, ...source }; // merged: { a: 1, b: 2 },target 不变
- 优势:简洁、不修改原对象
- 局限:仅适用于可枚举属性
2. 深拷贝合并
-
递归实现
function deepMerge(target, source) { const isObject = (obj) => obj && typeof obj === 'object'; if (!isObject(target) || !isObject(source)) { return source; } Object.keys(source).forEach(key => { const targetValue = target[key]; const sourceValue = source[key]; if (Array.isArray(targetValue) && Array.isArray(sourceValue)) { target[key] = targetValue.concat(sourceValue); } else if (isObject(targetValue) && isObject(sourceValue)) { target[key] = deepMerge({ ...targetValue }, sourceValue); } else { target[key] = sourceValue; } }); return target; }