Object.assign
suggest changeThe Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Use it to assign values to an existing object:
const user = {
firstName: "John"
};
Object.assign(user, {lastName: "Doe", age:39});
console.log(user); // Logs: {firstName: "John", lastName: "Doe", age: 39}
Or to create a shallow copy of an object:
const obj = Object.assign({}, user);
console.log(obj); // Logs: {firstName: "John", lastName: "Doe", age: 39}
Or merge many properties from multiple objects to one:
const obj1 = {
a: 1
};
const obj2 = {
b: 2
};
const obj3 = {
c: 3
};
const 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
Primitives will be wrapped, null and undefined will be ignored:
const var_1 = 'abc';
const var_2 = true;
const var_3 = 10;
const var_4 = Symbol('foo');
const obj = Object.assign({}, var_1, null, var_2, undefined, var_3, var_4);
console.log(obj); // Logs: { "0": "a", "1": "b", "2": "c" }
Note that, among these boxed primitives, only the string wrapper has own enumerable properties.
Use it to merge an array of users into one object. Assign into the accumulator; assigning into a fresh {} on every step would keep only the last user:
return users.reduce((result, user) => Object.assign(result, { [user.id]: user }), {});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents