How to merge objects in javascript?

Merge objects using the spread operator (…)

let obj1 = {
    name: 'David',
    age: 25,
    sub: 'English'
};

let obj2 = {
    address: 'UK',
   phone: '111111111'

};
let merged = {...obj1, ...obj2};

console.log(merged);
Output:
{
  name: 'David',
  age: 25,
  sub: 'English',
  address: 'UK',
  phone: '111111111'
}

Merge objects using Object.assign() method


let obj1 = {
    name: 'David',
    age: 25,
    sub: 'English'
};

let obj2 = {
    address: 'UK',
   phone: '111111111'

};
let merged = Object.assign(obj1, obj2);;

console.log(merged);
Output:
{
  name: 'David',
  age: 25,
  sub: 'English',
  address: 'UK',
  phone: '111111111'
}
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments