JavaScript

How to Merge Objects in JavaScript

In this tutorial, we are going to see different methods to merge objects in javascript. Either by using the assign() method or the spread operator on javascript/ES6.
 

Using the assign() method

We can use the Object.assign() method and assign the object’s properties to an empty object.

var obj1 = {abc: 10};

var obj2 = {xyz: 20};

var obj3 = Object.assign( {}, obj1, obj2 );

console.log(obj3);

Output:

{
  "abc": 10,
  "xyz": 20
}
 

Using the ES6 spread operator

In 2015, ES6 introduced the spread operator, which is the perfect way to merge two simple objects into one:

const obj1 = {
  abc: 10
}

const obj2 = {
  xyz: 20
}

const obj3 = {...obj1, ...obj2 }

console.log(obj3);

Output:

{
  "abc": 10,
  "xyz": 20
}
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *