对象合并
JavaScript 中合并对象的多种方法。
Object.assign()
const target = { a: 1, b: 2 };
const source1 = { b: 3, c: 4 };
const source2 = { d: 5 };
// 合并到 target
const result = Object.assign(target, source1, source2);
console.log(result); // { a: 1, b: 3, c: 4, d: 5 }
console.log(target); // { a: 1, b: 3, c: 4, d: 5 } - target 被修改
// 不修改原对象
const merged = Object.assign({}, target, source1, source2);
扩展运算符(推荐)
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const obj3 = { d: 5 };
// 合并
const merged = { ...obj1, ...obj2, ...obj3 };
console.log(merged); // { a: 1, b: 3, c: 4, d: 5 }
// 后覆盖前
const result = { ...obj2, ...obj1 };
console.log(result); // { b: 2, c: 4, a: 1 } - obj1 的 b 覆盖 obj2 的 b
合并深层对象
const obj1 = { a: 1, nested: { x: 1, y: 2 } };
const obj2 = { b: 2, nested: { y: 3, z: 4 } };
// 浅合并 - nested 会被完全覆盖
const shallow = { ...obj1, ...obj2 };
console.log(shallow); // { a: 1, b: 2, nested: { y: 3, z: 4 } }
// 深合并需要递归或使用库
function deepMerge(target, source) {
const result = { ...target };
for (const key in source) {
if (source.hasOwnProperty(key)) {
if (
typeof source[key] === 'object' &&
source[key] !== null &&
typeof result[key] === 'object' &&
result[key] !== null
) {
result[key] = deepMerge(result[key], source[key]);
} else {
result[key] = source[key];
}
}
}
return result;
}
const deep = deepMerge(obj1, obj2);
console.log(deep); // { a: 1, b: 2, nested: { x: 1, y: 3, z: 4 } }
条件合并
const config = {
name: 'app',
version: '1.0.0'
};
const userSettings = {
theme: 'dark',
language: 'zh'
};
// 只合并非空对象
const merged = {
...config,
...(userSettings || {})
};
// 根据条件合并
const enableFeature = true;
const result = {
...config,
...(enableFeature && { feature: 'enabled' })
};
使用 lodash merge
import _ from 'lodash';
const obj1 = { a: 1, nested: { x: 1 } };
const obj2 = { b: 2, nested: { y: 2 } };
// 深合并
const merged = _.merge({}, obj1, obj2);
console.log(merged); // { a: 1, b: 2, nested: { x: 1, y: 2 } }