Camkode
Camkode

How to Merge Objects in JavaScript

Posted by Kosal

How to Merge Objects in JavaScript

To merge objects in JavaScript, you can use the spread operator (...) or Object.assign() which can be used to merge two or more objects and create a new one that has properties of the merged objects. If objects have a property with the same name, then the right-most object property overwrites the previous one

Using spread operator (...)

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

Example:

const user = {
  firstName: "Kosal",
  lastName: "Ang",
  age: 30,
  country: "USA",
};

const profile = {
  jobTitle: "Programmer",
  country: "Cambodia",
  city: "Phnom Penh",
};

const employee = {
  ...user,
  ...profile,
};

console.log(employee);

Output

{
  "firstName": "Kosal",
  "lastName": "Ang",
  "age": 30,
  "country": "Cambodia",
  "jobTitle": "Programmer",
  "city": "Phnom Penh"
}

Using Object.assign()

Object.assign(target, sourceObj1, sourceObj2, ...);

Example:

const user = {
  firstName: "Kosal",
  lastName: "Ang",
  age: 30,
  country: "USA",
};

const profile = {
  jobTitle: "Programmer",
  country: "Cambodia",
  city: "Phnom Penh",
};

const employee = Object.assign(user, profile);

console.log(employee);

Output

{
  "firstName": "Kosal",
  "lastName": "Ang",
  "age": 30,
  "country": "Cambodia",
  "jobTitle": "Programmer",
  "city": "Phnom Penh"
}