Learn How to assign data to an Object in Javascript using Object.assign() method for Beginners

Javascript Object.assign() Method performs copying of data from one variable to another. It can also copy content from more than one variable.

Object.assign() method syntax

Object.assign(destination_object,to_be_copied_object 1,to_be_copied_object 2...);

We refer destination_object to the empty object create to which values and data must be copied. to_be_copied_object refers to those objects whose data is copied to `destination_object`. We’ll be using this term throughout this post.

Table of Contents

Assigning Values to Destination Object

Here there is an object x which has properties first_name, last_name and copy is destination_object to which data of an object x will be copied.

var x = {
    "first_name" : "Rohan",
    "last_name" : "Kumar",
};
var copy = {};
Object.assign(copy, x);            
console.log(copy);

//Console Output
{first_name: "Rohan", last_name: "Kumar"}
Assigning Values to Destination Object
Assigning Values to Destination Object

Copying functions to destination_object

var x = {
    "first_name" : "Rohan",
    "last_name" : "Kumar",
    "full_name" : function(){
        return this.first_name+" "+this.last_name;
    },
};
var copy = {};
Object.assign(copy, x);            
console.log(copy);
console.log(copy.full_name());

//Console Output
{first_name: "Rohan", last_name: "Kumar", full_name: ƒ}
Rohan Kumar

Assigning values from multiple objects

var x = {};
var y = {
    "first_name" : "Kiran",
};
var z = {
    "last_name" : "Ahuja"
};
Object.assign(x,y,z);
console.log(x);

//Console Output
{first_name: "Kiran", last_name: "Ahuja"}
Assigning values from multiple objects
Assigning values from multiple objects

We also use them when there are a lot of arguments to be passed to the class constructors.

class A{
    constructor(data){
        Object.assign(this,data);
        console.log(this);
    }
}

var obj_a = new A({"name" : "Susan", "age" : 16});

//Console Output
A {name: "Susan", age: 16}
using Object.assign() method is class constructor to assign all values from array data to this object
using Object.assign() method is a class constructor to assign all values from array data to this object

The this object refers to the current object obj_a. The Object.assign() method is overrides this object.

Conclusion

So it’s time to say bye we have come to the end of our post on Learn How to assign data to an Object in Javascript using Object.assign() method for Beginners. If you like our content then please do share it and comment to clarify your doubts. We thank you from bottom of our heart.

Related Posts

Summary
Review Date
Reviewed Item
Learn How to create an Object in Javascript using Object.assign() method for Beginners
Author Rating
51star1star1star1star1star
Software Name
Javascript Programming
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development