March 21, 2022

Using JavaScript Object.assign() method

In this post, we will see how to use the JavaScript Object.assign() method to copy and merge objects.

The syntax of the Object.assign() method is:

Object.assign(target, ...sources)

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

The Object.assign() invokes the getters on the source objects and setters on the target.

Clone an object

The following example uses the Object.assign() method to clone an object.

let book = {
    title: 'My Title'
};

let clonedBook = Object.assign({}, book);

console.log(clonedBook);
Output will contain the properties copied from source object.
{ title: 'My Title' }

Note that the Object.assign() only creates a shallow clone, not a deep clone.

Merge objects

The Object.assign() can merge two or more source objects into a target object which will contain properties consisting of all the properties of the source objects. For example:

let book = {
    title: 'My Title'
};

let bookTemplate = {
    noOfPage: 200,
    author: 'Author'
};

let bookPublishTemplate = {
    publisher: 'My Publisher',
    publishDate: '21-Mar-2022'
};

let newBook = Object.assign({}, book, bookTemplate, bookPublishTemplate);

console.log(newBook);
Output will contain the properties merged from all the source objects.
{
    title: 'My Title',
    noOfPage: 200,
    author: 'Author'
    publisher: 'My Publisher',
    publishDate: '21-Mar-2022'
}

If two or more source objects have the property with same name, the property of the later object overwrites the earlier one:

let book = {
    title: 'My Title'
};

let bookTemplate = {
    title: 'My Title from bookTemplate'
    noOfPage: 200,
    author: 'Author'
};

let bookPublishTemplate = {
    author: 'Author from bookPublishTemplate'
    publisher: 'My Publisher',
    publishDate: '21-Mar-2022'
};

let newBook = Object.assign({}, book, bookTemplate, bookPublishTemplate);

console.log(newBook);
Output will contain the properties merged from all the source objects, also the duplicate properties will be overwritten by the later source objects.
{
    title: 'My Title from bookTemplate'
    noOfPage: 200,
    author: 'Author from bookPublishTemplate'
    publisher: 'My Publisher',
    publishDate: '21-Mar-2022'
}

1 comment:

  1. Great post! I am actually getting ready to cross this information, it is very helpful me. Also a great blog here with all of the valuable information you have. Keep up the good work you are doing here. HealthSpott

    ReplyDelete