Monday, December 24, 2018

Understanding Object.assign() in javascript

This explains explains what is Object.assign() in javascript. Basically Object.assign() copies the values (of all enumerable own properties) from one or more source objects to a target object. It has a signature of Object.assign(target, ...sources). The target object is the first parameter and is also used as the return value. Object.assign() is useful for merging objects or cloning them shallowly.

Understanding Object.assign() in javascript

Lets see the below example to build more understanding on Object.assign() in javasript.


Merging an object : 

// Merge an object
let first = {Firstname: 'skptricks'};
let last = {LastName: 'kumar'};
let person = Object.assign(first, last);

// printing the person variable value...
console.log(person);

// printing the targeted object value...
console.log(first);

Output :
----------------------
> Object { Firstname: "skptricks", LastName: "kumar" }
> Object { Firstname: "skptricks", LastName: "kumar" }

Merge multiple sources :

// Merge multiple sources
let a = Object.assign({a: 0}, {b: 1}, {c: 2});
console.log(a);

Output :
----------------------
> Object { a: 0, b: 1, c: 2 }

Merge and overwrite equal key :

// Merge and overwrite equal keys
let a = Object.assign({a: 0}, {a: 1}, {a: 2});
console.log(a);

Output :
----------------------
> Object { a: 2 }

Clone an object :

// Clone an object
let obj = {a: 0, b: 1}
let clone = Object.assign({}, obj);
console.log(clone);

Output :
----------------------
> Object { a: 0, b: 1 }

This is all about Object.assign() in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment