Javascript Tutorial Object.assign()

Many times you have an object and you want to clone or combine property of different objects to one object.

Let’s check how to do that with Object.assign().

The syntax of Object.assing is:

Object.assign(target, ...sources)

Suppose we have one object like the following:

let Employee = { name : 'Pietro', age : 44, Sex : 'male'};

We have also another object called EmployeeRecord which is as the following

let EmployeeRecord = {
name : 'Pietro', address : 'Colorado Avenue 45 Miami', seriority : 15, category_employee : 'Cat A'
};

Now we want to have a new object (t) which combines all properties of Employee and EmployeeRecord we can use the following command:

let t = Object.assign(Emnployee,EmployeeRecord)

Here is what will happen if we print to console the 3 objects above

As you can see if we print the new object “t” to console we can notice that this object has all the properties of the first object (Empployee) and also all properties of the second object (EmployeeRecord)

It is important to know that if one property has different value the property of the last object will overwrite the property of the first one.

We can verify that by changing slightly our previous example

let EmployeeRecord = {
name : 'Pietro2', address : 'Colorado Avenue 45 Miami', seriority : 15, category_employee : 'Cat A'
};

In this case the name property if different from the two objects.

If we re-run create a variable t and we assign both Employee and EmployeeRecprd

Please notice that now the name property is not Pietro but Pietro2.

Leave a Reply

Your email address will not be published. Required fields are marked *