JavaScript ES6 Object Extensions - Object.assign()

JavaScript ES6 Object Extensions - Object.assign()
----------------------------------------------

In this topic, we will cover the javascript ES6 Object extensions method which is Object.assign()

JavaScript Object.assign()

The Object.assign() copies all the values and properties from one or more source objects to a target object means own properties from the source objects to the target object. It returns the target object. 

Using Object.assign() to clone an object.

const sourceObj = { name:"coderuck",author:"editor"};
const targetObj = Object.assign({},sourceObj);

//Display the target object
console.log(targetObj);

A most important point to note is that the Object.assign() only make a shallow clone, not a deep clone. 

Now we will use Object.assign() to merge multiple objects.

const sourceObjOne = { name:"coderuck",author:"editor"};
const sourceObjTwo = { website:"https://coderuck.com/"};
const targetObj = Object.assign({},sourceObjOne , sourceObjTwo );

//Display the target object
console.log(targetObj);

//Output
{name: 'coderuck', author: 'editor', website: 'https://coderuck.com/'}

If the source objects have the same property, the property of the later object overwrites the earlier one:

const sourceObjOne = { name:"coderuck",author:"editor"};
const sourceObjTwo = { website:"https://coderuck.com/",author:"coderuck-editor"};
const targetObj = Object.assign({},sourceObjOne , sourceObjTwo );

//Display the target object
console.log(targetObj);

//Output
{name: 'coderuck', author: 'coderuck-editor', website: 'https://coderuck.com/'}

As you have checked the output first object and second have the same property because of that second property overrides the first property.

Categories: Java Script Tags: #ES6, #JavaScript,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.