Object.assign() Method – Assign an Object's Properties to Another Object
Whenever you use Object.assign() on two or more JavaScript objects, the method does the following:
- It copies the source objects’ enumerable own properties and assigns them to the target object.
- It returns the updated target object.
Syntax of the Object.assign()
Method
Object.assign()
accepts multiple arguments. Here’s the syntax:
Object.assign(targetObj, sourceObj1, ..., sourceObjN)
- The
targetObj
argument refers to the JavaScript object you want to modify. - The
sourceObj1, ..., sourceObjN
arguments specify one or more objects whose enumerable own properties you wish to copy to thetargetObj
.
Examples of the Object.assign()
Method
Below are examples of the Object.assign()
method.
Copy colors
’ properties into the profile
object
const profile = { firstName: "Oluwatobi", lastName: "Sofela",};
const colors = { car: "White", shoe: "Pink",};
const aboutMe = Object.assign(profile, colors);
console.log(aboutMe);
// The invocation above will return:{ firstName: "Oluwatobi", lastName: "Sofela", car: "White", shoe: "Pink" }
Copy food
and fact
’s properties into the capital
object
const capital = { india: "New Delhi", unitedStates: "Washington, D.C.",};
const food = { spicy: "Chicken Chettinad", confection: "S'more", dessert: "Trifle",};
const fact = { strongestCurrency: "Kuwaiti Dinar",};
const capitalsFoodNFacts = Object.assign(capital, food, fact);
console.log(capitalsFoodNFacts);
// The invocation above will return:{ india: "New Delhi", unitedStates: "Washington, D.C.", spicy: "Chicken Chettinad", confection: "S'more", dessert: "Trifle", strongestCurrency: "Kuwaiti Dinar" }
Copy companyProfile
’s properties into myProfile
object
const myProfile = { firstName: "Oluwatobi", lastName: "Sofela", npmPackage: "@codesweetly/react-youtube-playlist",};
const companyProfile = { companyName: "CodeSweetly", npmPackage: "react-image-grid-gallery",};
const bio = Object.assign(myProfile, companyProfile);
console.log(bio);
// The invocation above will return:{ firstName: "Oluwatobi", lastName: "Sofela", npmPackage: "react-image-grid-gallery", companyName: "CodeSweetly" }
Notice that the companyProfile
’s npmPackge
property replaced that of myProfile
.
The replacement happened because the two properties have the same key (property name). And in such a case, the sourceObj
’s property overwrites that of the targetObj
.
Important Stuff to Know about the Object.assign()
Method
Keep these three essential pieces of info in mind whenever you choose to use the Object.assign()
method.
Info 1: The source object can be an array or a string value
The Object.assign()
method accepts array item and string primitives as a source object.
Here’s an example:
const myName = "Oluwatobi";const bio = Object.assign({}, myName);
console.log(bio);
// The invocation above will return:{ 0: "O", 1: "l", 2: "u", 3: "w", 4: "a", 5: "t", 6: "o", 7: "b", 8: "i" }
Here’s another example:
const myName = ["Oluwatobi", "Sofela", "CodeSweetly" ];const bio = Object.assign({}, myName);
console.log(bio);
// The invocation above will return:{ 0: "Oluwatobi", 1: "Sofela", 2: "CodeSweetly" }
Info 2: How does Object.assign()
work on objects containing only primitive values?
Suppose you used the Object.assign()
method on a source object containing only primitive values. In that case, the computer will not create any reference between the original object and the duplicated one.
For instance, consider the following code:
const myName = { firstName: "Oluwatobi", lastName: "Sofela" };const bio = Object.assign({}, myName);
console.log(bio); // { firstName: "Oluwatobi", lastName: "Sofela" }
Observe that every item in myName
is a primitive value. Therefore, when we used the Object.assign()
method to assign myName
’s properties to the empty target object, the computer did not create any reference between the two objects.
As such, any alteration you make to myName
will not reflect in bio
, and vice versa.
As an example, let’s add more content to myName
:
myName.firstName = "Tobi";
Now, let’s check the current state of myName
and bio
:
console.log(myName); // { firstName: "Tobi", lastName: "Sofela" }console.log(bio); // { firstName: "Oluwatobi", lastName: "Sofela" }
Notice that myName
’s updated content did not reflect in bio
—because Object.assign()
created no reference between the source and the target object.
Info 3: How does Object.assign()
work on objects containing one or more non-primitive values?
Suppose you used the Object.assign()
method on a source object containing one or more non-primitives. In that case, the computer will create a reference between the original non-primitive and the cloned one.
Here is an example:
const myName = { fullName: { firstName: "Oluwatobi", lastName: "Sofela" },};
const bio = Object.assign({}, myName);
console.log(bio); // { fullName: { firstName: "Oluwatobi", lastName: "Sofela" } }
Observe that myName
contains a non-primitive value.
Therefore, using the Object.assign()
method to assign myName
’s properties to the empty target object caused the computer to create a reference between the two objects.
As such, any alteration you make to myName
’s copy will reflect in bio
’s version and vice versa.
As an example, let’s add more content to myName
:
myName.fullName.firstName = "Tobi";
Now, let’s check the current state of myName
and bio
:
console.log(myName); // { fullName: { firstName: "Tobi", lastName: "Sofela" } }console.log(bio); // { fullName: { firstName: "Tobi", lastName: "Sofela" } }
Notice that myName
’s updated content is reflected in bio
—because Object.assign()
created a reference between the source and the target object.
Shallow Copy vs. Deep Copy: What’s the Difference?
You do shallow copy when you create references while cloning one object’s properties into another.
For instance, consider this snippet:
const myName = { fullName: { firstName: "Oluwatobi", lastName: "Sofela" },};
const bio = Object.assign({}, myName);
console.log(bio); // { fullName: { firstName: "Oluwatobi", lastName: "Sofela" } }
myName.fullName.firstName = "Tobi";
console.log(myName); // { fullName: { firstName: "Tobi", lastName: "Sofela" } }console.log(bio); // { fullName: { firstName: "Tobi", lastName: "Sofela" } }
Object.assign({}, myName)
produces a shallow copy of the myName
object because whatever alteration you make in one will reflect in the other. In other words, bio
’s detachment from myName
is shallow since they still have some connections.
You do deep copy when you clone objects without creating references. The JSON.parse(JSON.stringify())
and structuredClone()
methods are tools you can use to create a deep copy.
Here’s an example:
const myName = { fullName: { firstName: "Oluwatobi", lastName: "Sofela" },};
const bio = JSON.parse(JSON.stringify(myName));
myName.fullName.firstName = "Tobi";
console.log(myName); // { fullName: { firstName: "Tobi", lastName: "Sofela" } }console.log(bio); // { fullName: { firstName: "Oluwatobi", lastName: "Sofela" } }
The snippet above used the JSON.parse(JSON.stringify())
method to clone myName
into bio
without creating any reference (deep copy). In other words, bio
’s detachment from myName
is deep since they no longer have any connections.
Here’s another example:
const myName = { fullName: { firstName: "Oluwatobi", lastName: "Sofela" },};
const bio = structuredClone(myName);
myName.fullName.firstName = "Tobi";
console.log(myName); // { fullName: { firstName: "Tobi", lastName: "Sofela" } }console.log(bio); // { fullName: { firstName: "Oluwatobi", lastName: "Sofela" } }
The snippet above used the structuredClone()
method to clone myName
into bio
without creating any reference (deep copy). In other words, bio
’s detachment from myName
is deep since they no longer have any connections.
You can break off the reference between two connected objects by replacing any of the two with a new object.
Here’s an example:
// Create a deep object:const myName = { fullName: { firstName: "Oluwatobi", lastName: "Sofela" },};
// Create a shallow copy of myName:const bio = Object.assign({}, myName);
// Change myName's firstName:myName.fullName.firstName = "Tobi";
// Check myName's content:console.log(myName); // { fullName: { firstName: "Tobi", lastName: "Sofela" } }
// Check bio's content:console.log(bio); // { fullName: { firstName: "Tobi", lastName: "Sofela" } }
// Notice that myName and bio are linked. Let's break the connection:myName.fullName = { firstName: "Oluwa", lastName: "Sofela" };
// Check myName's content:console.log(myName); // { fullName: { firstName: "Oluwa", lastName: "Sofela" } }
// Check bio's content:console.log(bio); // { fullName: { firstName: "Tobi", lastName: "Sofela" } }
The snippet above disconnected the pointer between myName
and bio
’s fullName
objects by reassigning myName.fullName
with a new object.