AppDividend
Latest Code Tutorials

Javascript Object Assign Example | JS Object.assign()

2

Javascript Object assign() is an inbuilt function that used to copy the values of all own enumerable properties from one or more source objects to the target object.  Object.assign() method will return a target object. Javascript Object.assign() method is used for cloning an object. It is used to merge objects with the same properties.

The properties in the sources will overwrite properties in a target object if they have the same key.

Content Overview

#Javascript Object Constructor

In the object-oriented programming world, we already know the importance of classes and objects, but unlike all the other programming languages, JavaScript does not have any traditional classes that seen in different programming languages, but JavaScript has objects and constructors which work mostly in the same way to perform the same kind of operations.

There are two types of constructors in JavaScript,

1) Built-in constructors(array and object)

2) Custom constructors(define properties and methods for specific objects).

The Object constructor creates the object wrapper for the given value.

If a value is null or undefined, it will create and return the empty object; Otherwise, it will return the object of a type that corresponds to a given value.

If the value is the object already, it will return the value.

When called in the non-constructor context, Object behaves identically to new Object().

#Properties of the Object constructor

  1. Object.length

    It has a value of 1.

  2. Object.prototype

    It allows the addition of properties to all objects of the type Object. Methods of the Object constructor.

Javascript Object.assign() method

JS Object.assign() copies the values (of all own enumerable properties) from one or more source objects to the target object.

It has the signature of Object.assign(target, …sources). The target object is the first parameter and is also used as the return value.

Javascript Object.assign() is useful for merging the objects or cloning them shallowly.

So, from the many Object constructor methods,  Object.assign() is one method that is used to copy the values and properties from one or more source objects to a target object. The syntax for a Javascript Object assign() method is the following.

Object.assign(target, ...sources)

A target parameter is a target object.

The sources parameter are the objects that need to be cloned.

Let us take a simple example by cloning the object.

// app.js

let obj = { name: 'Krunal', surname: 'Lathiya' };
let cloneObj = Object.assign({}, obj);
console.log(cloneObj);

In the above example, we have defined one object, and then we have created a clone of that object with a new object. The output will be the following.

Javascript Object Assign Example | Object.assign() Tutorial

So, it has copied all the properties from a source object.

Let us merge three objects with Object.assign() method.

// app.js

let o1 = { a: 21 };
let o2 = { b: 22 };
let o3 = { c: 24 };

Object.assign(o1, o2, o3);
console.log(o1);

Javascript Object Assign Example

#Merging objects with the same properties

If the properties get repeated inside the source objects, then in the clone object, the repeated properties will be skipped, and we only get the unique properties on the target object.

// app.js

let o1 = { a: 21, b: 22, c: 24 };
let o2 = { b: 22, c: 24 };
let o3 = { c: 24 };

let finalObj = Object.assign({}, o1, o2, o3);
console.log(finalObj);

Object.assign() Tutorial

#Immutablity of Object.assign() method

Let’s see the following example.

// app.js

let obj = {
  eleven: 'Millie Bobby Brown',
  mike: 'Finn Wolfhard',
};
let objCopy = Object.assign({}, obj);
console.log(objCopy);

objCopy.mike = 'Noah Schnapp';
console.log(objCopy);
console.log(obj);

See the output.

➜  es git:(master) ✗ node app
{ eleven: 'Millie Bobby Brown', mike: 'Finn Wolfhard' }
{ eleven: 'Millie Bobby Brown', mike: 'Noah Schnapp' }
{ eleven: 'Millie Bobby Brown', mike: 'Finn Wolfhard' }
➜  es git:(master) ✗

In the code above, we changed the value of a property ‘mike’ in objCopy object to ‘Noah Schnapp‘, and when we log a modified objCopy object in the console, the changes only apply to objCopy.

The last line of the code checks that the obj object is still intact and hasn’t changed.

This means that we have successfully created the copy of a source object without any references to it.

#Pitfall of Object.assign() In Javascript

Let’s discuss a little bit about shallow copying. See the following code example.

// app.js

let obj = {
  a: 11,
  b: {
    c: 21,
  },
}
let newObj = Object.assign({}, obj);
console.log('First use of Object.assign() method')
console.log(newObj);
console.log('-------------------------------')

obj.a = 10;
console.log('Modify the obj\'s "a" property');
console.log(obj);
console.log(newObj);
console.log('-------------------------------')

newObj.a = 19;
console.log('Modify the newObj\'s "a" property');
console.log(obj);
console.log(newObj);
console.log('-------------------------------')

newObj.b.c = 29;
console.log('Modify the newObj\'s "b"\'s "c" property');
console.log(obj);
console.log(newObj);

See the output.

➜  es git:(master) ✗ node app
First use of Object.assign() method
{ a: 11, b: { c: 21 } }
-------------------------------
Modify the obj's "a" property
{ a: 10, b: { c: 21 } }
{ a: 11, b: { c: 21 } }
-------------------------------
Modify the newObj's "a" property
{ a: 10, b: { c: 21 } }
{ a: 19, b: { c: 21 } }
-------------------------------
Modify the newObj's "b"'s "c" property
{ a: 10, b: { c: 29 } }
{ a: 19, b: { c: 29 } }
➜  es git:(master) ✗

So, here Properties on the prototype chain and non-enumerable properties cannot be copied.

#Deep copy of an object in Javascript

A deep copy will duplicate the every object it encounters.

The copy and the original object will not share anything so that it will be the copy of the original.

JSON.parse(JSON.stringify(object));

I have already written one article on how we can parse JSON in Javascript.

This fixes the issue we had earlier. Now, newObj.b has a copy and not a reference! This is a way to deep copy objects. 

See the following code example.

// app.js

let obj = {
  a: 11,
  b: {
    c: 21,
  },
}

let newObj = JSON.parse(JSON.stringify(obj));
obj.b.c = 29;
console.log(obj);
console.log(newObj);

See the output.

➜  es git:(master) ✗ node app
{ a: 11, b: { c: 29 } }
{ a: 11, b: { c: 21 } }
➜  es git:(master) ✗

Finally, Object.assign() In Javascript | Object Assign Example In Javascript tutorial is over.

Recommended Posts

Javascript Object.freeze() Example

Javascript Object.toString() Example

Javascript Object.values() Example

Javascript Object.keys() Example

Javascript Object.create() Example

2 Comments
  1. ngoc danh says

    tks friend

  2. good says

    Object.assign doesn’t show immutability. Here it only shows the difference of assignment by copy and by reference.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.