JS中Object.assign的使用(属性拷贝)

前言

Object.assign 是 JavaScript 中的一个方法,用于将一个或多个源对象的所有可枚举属性拷贝到目标对象。它的基本作用是实现对象的合并或属性的赋值。

复制属性

语法

1
Object.assign(target, ...sources)

参数

  • target: 目标对象,属性将被拷贝到这个对象上。
  • sources: 一个或多个源对象,从中拷贝属性到目标对象。

示例1

1
2
3
4
5
6
const target = { a: 1 };
const source = { b: 2, c: 3 };

Object.assign(target, source);

console.log(target); // 输出: { a: 1, b: 2, c: 3 }

示例2

1
2
3
4
5
6
7
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const obj3 = { c: 3 };

const merged = Object.assign({}, obj1, obj2, obj3);

console.log(merged); // 输出: { a: 1, b: 2, c: 3 }

注意事项

  • 浅拷贝: Object.assign 执行的是浅拷贝,如果源对象的属性值是对象类型,那么目标对象中的属性值仍然是对源对象中对象的引用。
  • 属性的顺序: 如果多个源对象中包含相同的属性,后面的源对象中的属性值会覆盖前面源对象中的属性值。
  • 不可枚举属性: Object.assign 只会拷贝可枚举属性,不会拷贝不可枚举的属性。

只复制有值的属性

Object.assign 本身不会自动过滤掉值为 undefinednull 的属性。如果你希望在合并对象时只包含那些值为非 undefined 或非 null 的属性,你可以通过自定义函数来实现这一点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function assignNonEmpty(target, ...sources) {
sources.forEach(source => {
Object.keys(source).forEach(key => {
if (source[key] !== undefined && source[key] !== null) {
target[key] = source[key];
}
});
});
return target;
}

// 示例用法
const obj1 = { a: 1, b: null };
const obj2 = { b: 2, c: undefined, d: 4 };

const result = assignNonEmpty({}, obj1, obj2);
console.log(result); // 输出: { a: 1, b: 2, d: 4 }

在这个示例中,assignNonEmpty 函数会遍历每个源对象,并将那些值既不为 undefined 也不为 null 的属性合并到目标对象中。

这样,合并后的对象只包含有实际值的属性。

只复制有值且目标有的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function assignOnlyExistingAndNonEmpty(target, ...sources) {
const keysToUpdate = Object.keys(target);

sources.forEach(source => {
Object.keys(source).forEach(key => {
if (keysToUpdate.includes(key) && source[key] !== undefined && source[key] !== null) {
target[key] = source[key];
}
});
});

return target;
}

// 示例用法
const target = { a: 1, b: 2, c: 3 };
const source1 = { a: null, b: 4, d: 5 };
const source2 = { b: undefined, c: 6 };

const result = assignOnlyExistingAndNonEmpty(target, source1, source2);
console.log(result); // 输出: { a: 1, b: 4, c: 6 }