In this tutorial, you’ll learn how to merge two objects in JavaScript. You’ll use two ways to do it. One using Object.assign and another one using ES6 Spread operator.

Merge Two Objects Using Object.assign

const emp = {
  "name" : "Roy",
  "age" : "30"
}
const empDetails = {
  "currentLocation" : "Dubai",
  "country" : "USA"
}

let result = Object.assign({},emp,empDetails)
console.log(result);

The first parameter to Object.assign is the target object and the target object is returned after merging the objects.

Merge Two Objects Using ES6 Spread Operator

const emp = {
  "name" : "Roy",
  "age" : "30"
}
const empDetails = {
  "currentLocation" : "Dubai",
  "country" : "USA"
}

let result = {...emp, ...empDetails}
console.log(result);

As the name suggests ES6 spread operator spreads the objects and combines it into a single object.

Note : If there is a same key value pair in the source objects, it replaces the target object.

const emp = {
  "name" : "Roy",
  "age" : "30"
}
const empDetails = {
  "currentLocation" : "Dubai",
  "country" : "USA",
  "name" : "Hari"
}

let result = {...emp, ...empDetails}
let res = Object.assign({}, emp, empDetails);

The above code outputs the object with name as Hari.

{
  age: "30",
  country: "USA",
  currentLocation: "Dubai",
  name: "Hari"
}