该方法用于将所有可枚举的自身属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。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); // 日志:{a:1,b:2,c:3} console.log(obj1); // 日志:{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})