AppDividend
Latest Code Tutorials

Javascript Object Assign Example | Object.assign() Tutorial

0 81

Get real time updates directly on you device, subscribe now.

Javascript Object Assign Example | Object.assign() Tutorial is today’s topic. Javascript Object.assign() method is used to copy the values of all own enumerable properties from one or more source objects to the target object.  It will return a target object. Object.assign() is used for cloning an object. Object.assign() is used to merge object with same properties. Properties in a target object will be overwritten by the properties in the sources if they have a same key.

If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Javascript Object Assign Example

So, from the many Object constructor methods,  Object.assign() is one method which is used to copy the values and properties from one or more source objects to a target object. The syntax for a Javascript Object assign() method is following.

Object.assign(target, ...sources)

A target parameter is a target object.

The sources parameter are the objects that need to be cloned.

Let us take a simple example by cloning the object.

// app.js

let obj = { name: 'Krunal', surname: 'Lathiya' };
let cloneObj = Object.assign({}, obj);
console.log(cloneObj);

In the above example, we have defined one object, and then we have created a clone of that object with a new object. The output will be following.

Javascript Object Assign Example | Object.assign() Tutorial

So, it has copied all the properties from a source object.

Let us merge three objects with Object.assign() method.

// app.js

let o1 = { a: 21 };
let o2 = { b: 22 };
let o3 = { c: 24 };

Object.assign(o1, o2, o3);
console.log(o1);

Javascript Object Assign Example

Merging objects with the same properties

If the properties get repeated inside the source objects then in the clone object, the repeated properties will be skipped, and we only get the unique properties on the target object.

// app.js

let o1 = { a: 21, b: 22, c: 24 };
let o2 = { b: 22, c: 24 };
let o3 = { c: 24 };

let finalObj = Object.assign({}, o1, o2, o3);
console.log(finalObj);

Object.assign() Tutorial

Finally, Javascript Object Assign Example | Object.assign() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.