The Javascript Asign() Method to Merge and Clone Objects

by Luigi Nori Date: 11-08-2020 javascript asign objects


In this article, we will be covering Object.assign() method in javascript in detail with examples.
A javascript object is a collection of key-value pairs. Keys are also known as properties of object.
Keys are unique but values may be duplicate. Example of a javascript object is

let car = {
brand: 'Hyundai',
fuel: 'Petrol',
model: 'i20'
}

Here, car is an object with three properties or keys.
Object.assign
Object.assign() is used on javascript objects for copying or adding properties of one or more objects to another object. Object.assign() was introduced in javascript ES6.
It can be used to

1. Merge properties of multiple objects into one object.
2. Clone a javascript object.

Definition of Object.assign() as per the javascript docs is

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

where enumerable means the properties which can be loop over or iterated using a for-in loop and own properties means the properties which belong directly to the object and not to the parent object.

Syntax to use Object.assign() is

Object.assign(target, …sources)
  • sources are one or more object separated by a comma.
    Object.assign will copy the properties of all source objects into target object.
  • target may be a new object or an already existing object.

Object.assign() returns the target object with all the properties from source objects copied into it.
If any of the source objects contain same properties or keys with different values, then the value of last source object overwrites the previous value.

Object.assign example
Below is an example of Object.assign() where it copies the properties of two objects into a third object.
const objectOne = { x:1,y:2 };
const objectTwo = { z:3 };
const objectThree = {};
Object.assign(objectThree, objectOne, objectTwo);
console.log(objectThree);

Above example prints

{ x:1, y:2, z:3 }

It copied the properties from two objects into the third or target object. Note that the first argument to Object.assign() is the target object.
Another way of using Object.assign() is by supplying an empty object as first argument and assigning the returned value to a variable as

const objectThree = Object.assign({}, objectOne, objectTwo);

The example above shows how to merge objects with Object.assign() .
Object.assign with common properties
Below example shows the behavior when source objects have a property in common.

const objectOne = { x:1,y:2 };
const objectTwo = { z:3,y:4 };
const objectThree = {};
Object.assign(objectThree, objectOne, objectTwo);
console.log(objectThree);

In the above example, source objects have a property in common. It prints

{ x:1, y:4, z:3 }

Property of later object overwrites the earlier one. If you reverse the order of source objects as

Object.assign(objectThree, objectTwo, objectOne);

then the result will be

{ x:1, y:2, z:3 }

It is not necessary that target object is always empty, it may already have some properties. In this case, all the properties of source objects are merged into its own properties.
If the target object has common properties as source objects, then their values are overwritten by source properties.

Clone object
Object.assign() is used to create a copy or clone a javascript object as shown below. Notice the first argument to Object.assign() is an empty object.

const original = { x:1,y:2 };
const clone = Object.assign({}, original);
console.log('Original object');
console.log(original)
console.log('Clone object');
console.log(clone)

This prints

Original object

{x: 1, y: 2}

Clone object
{x: 1, y: 2}

which shows that the properties of source object is copied into target object.
Now if you change the value of a source object property, target object remains unchanged as below.

const original = { x:1,y:2 };
// clone object
const clone = Object.assign({}, original);
// modify source object property value
original.x = 5
console.log('Original object');
console.log(original)
console.log('Clone object');
console.log(clone)

Original object

{x: 5, y: 2}

Clone object
{x: 1, y: 2}

Value of source object property was modified but cloned object remains the same. This means that we have successfully created a clone object.

Clone created using this method is a shallow copy. This means that if the value of a source object property is another object, then its reference is copied.
Thus, if you change the value of a nested object property for source object, then the change will also be done in cloned object. Example,

// containes a nested object
const original = { x:1,y:{a:2} };
// clone object
const clone = Object.assign({}, original);
// modify nested property value
original.y.a = 5
console.log('Original object');
console.log(original)
console.log('Clone object');
console.log(clone)

This prints

Original object

{x: 5, y: {a:5}}

Clone object
{x: 1, y: {a:5}}

It changed the value for cloned object as well.
For deep cloning, use other object cloning methods.

Browser Support
Below is a list of minimum versions of different browsers which support Object.assign() .
Browser Version
Chrome 45
Firefox 34
Safari 9
Edge 12
IE No support
Opera 32

Hope the article was helpful to explain the usage of Object.assign() method in javascript.

 
by Luigi Nori Date: 11-08-2020 javascript asign objects hits : 1163  
 
Luigi Nori

Luigi Nori

He has been working on the Internet since 1994 (practically a mummy), specializing in Web technologies makes his customers happy by juggling large scale and high availability applications, php and js frameworks, web design, data exchange, security, e-commerce, database and server administration, ethical hacking. He happily lives with @salvietta150x40, in his (little) free time he tries to tame a little wild dwarf with a passion for stars.

 
 
 

Related Posts

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The package managers npm and yarn: main differences

Npm and yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that…

All the javascript functions and methods to manipulate arrays

This article will show that the prominent JavaScript array functions are .map(), .filter(), and .reduce(), and will then go through examples of instances in which .every() and .some() would save…

TypeScript: The evolution of JavaScript

When you're involved in the development of a large project, programming languages like JavaScript don't seem to be the best solution. Their lack of elements such as Language Aids has…

Awesome JavaScript Games and Js Software to create Games

Best sites js13kGames 2019 - Highlights from the js13kGames 2019 competition. js13kGames 2018 - 13 Games in ≤ 13kB of JavaScript. js13kGames 2017 - Build a game in 13kB or less with js13kGames. Adventure Triangle:…

Is JavaScript good for machine learning?

One of the things you always hear when you are talking to someone related to the M.L. world is that, one must learn Python because the vast majority of the…

First steps into JavaScript – a practical guide 3

After we learned the basic ofaccessing DOM elementsandhow to modify them,we are ready for the more exciting parts – handling DOM events. This allows us to make our web way more…

JavaScript: Promises explained with simple real life examples

Handling asynchronous data flows is complex, who hasn't faced codes like this one?: checkWeather('palma de mallorca', (error, weather) => { if (error) throw error; if (weather === 'well') { return checkFlights('palma…

First steps into JavaScript – a practical guide 2

In the previous aticleFirst steps into JavaScript – a practical guidewe covered the basics of the DOM and its relation to us becoming JS literate. Now that we know how…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration