Using Object.assign
The Object.assign()
method works by copying over the values and properties of another object (referred to as the source object) into the object we are trying to update (referred to as the target object).
There are several ways we can use Object.assign()
to merge our objects. The first way is to simply pass in the original object we want to be updated as the first argument and the other object containing the data we want to merge as the second argument.
Object.assign(target, source);
The problem with this though is that it mutates the original object. So if we don’t want our original object to be mutated we can instead pass in an empty object as the first argument.
Object.assign({}, target, source);
This will assign all of the properties and values from both the target and source objects into a brand new object.
We can also add more objects as arguments to be merged along with the other objects we’re copying data from. This can be done by passing in the object inline as an argument or defining it first and then passing it in.
Object.assign({}, target, source, { name: "Bob" }); // inline
const name = { name: "Bob" }; // predefined object
Object.assign({}, target, source, name);
Using the spread operator
The spread operator is another common method that happens to be more relevant for merging the properties and values of one object into another. I find it to be much simpler and more readable than using Object.assign()
.
To use the spread operator we precede the object we want to copy data from with ...
when passing it in.
const userData = {
name: "",
email: "",
password: ""
};
const newUserData = {
name: "Bob",
email: "bob@email.com",
password: "bobspassword"
};
const updatedUser = {...userData, ...newUserData};
This will extract out all of the properties and values merging them into a brand new user object.
If we want to add more properties we can do so just as we did before with Object.assign()
passing in the property inline or as a predefined object.
const updatedUser = {...userData, ...newUserData, updated: true};
This will give us a new object with all of the properties merged in and the added property of updated set to true.
{
email: "bob@email.com",
name: "Bob",
password: "bobspassword",
updated: true
}
Top comments (0)