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})