Merge Properties of Two Objects in JavaScript

This is a preview lesson
Register or sign in to take this lesson.

This tutorial shows how to merge properties of two objects. There are three ways of achieving this merger.

  • ECMAScript 2018
  • ECMAScript 2015
  • Before ECMAScript 2015

Example 1: ECMAScript 2018

We can achieve merger between two or more objects by using ... spread operator.

let locationInfo = {
    addressOne: "Kathmandu"
}
let user = {
    name: "Scanskill",
    rollNo: 1,
}

let userDetail = { ...user, ...locationInfo };
console.log("User Detail: ",userDetail);

The assign is not limited to two objects.

Output
User Detail: { name: "Scanskill", rollNo: 1, addressOne: "Kathmandu" }

Example 2: ECMAScript 2015

We can achieve this merger by using Object.assign() method.

let locationInfo = {
    addressOne: "Kathmandu"
}
let user = {
    name: "Scanskill",
    rollNo: 1,
}

let userDetail = Object.assign({}, user, locationInfo);
console.log("User Detail: ",userDetail);

Here the empty {} object is the target of merger between user and locationInfo. The assign is not limited to two objects.

Output
User Detail: { name: "Scanskill", rollNo: 1, addressOne: "Kathmandu" }

Example 3: Before ECMAScript 2015

We can achieve this merger by using for in loop.

let locationInfo = {
    addressOne: "Kathmandu"
}
let user = {
    name: "Scanskill",
    rollNo: 1,
}

let userDetail = {};
for(let attribute in user) {
    userDetail[attribute] = user[attribute];
}
for(let attribute in locationInfo) {
    userDetail[attribute] = locationInfo[attribute];
}

console.log("User Detail: ",userDetail);

Here, for in loop in created for each new merge between two objects.

Output
User Detail: { name: "Scanskill", rollNo: 1, addressOne: "Kathmandu" }