Object.assign
所述 Object.assign()
方法被用于从一个或多个源对象中所有可枚举自己的属性的值复制到目标对象。它将返回目标对象。
使用它为现有对象赋值:
var user = {
firstName: "John"
};
Object.assign(user, {lastName: "Doe", age:39});
console.log(user); // Logs: {firstName: "John", lastName: "Doe", age: 39}
或者创建对象的浅表副本:
var obj = Object.assign({}, user);
console.log(obj); // Logs: {firstName: "John", lastName: "Doe", age: 39}
或者将多个对象中的许多属性合并为一个:
var obj1 = {
a: 1
};
var obj2 = {
b: 2
};
var obj3 = {
c: 3
};
var obj = Object.assign(obj1, obj2, obj3);
console.log(obj); // Logs: { a: 1, b: 2, c: 3 }
console.log(obj1); // Logs: { a: 1, b: 2, c: 3 }, target object itself is changed
将封装基元,null 和 undefined 将被忽略:
var var_1 = 'abc';
var var_2 = true;
var var_3 = 10;
var var_4 = Symbol('foo');
var obj = Object.assign({}, var_1, null, var_2, undefined, var_3, var_4);
console.log(obj); // Logs: { "0": "a", "1": "b", "2": "c" }
注意,只有字符串包装器可以拥有自己的可枚举属性
将它用作 reducer :(将数组合并到一个对象)
return users.reduce((result, user) => Object.assign({}, {[user.id]: user})