How to merge two objects in JavaScript

Learn how to merge 2 JavaScript objects and create a new object that combines attributes


ES6Launched in 2015Spread operator, This is the perfect way to merge two simple objects into one:

const object1 = {
  name: 'Flavio'
}

const object2 = { age: 35 }

const object3 = {…object1, …object2 }

If two objects have a property with the same name, the second object property will overwrite the first object.

In this case, the best solution is to use Lodash and itsmerge()method, It will perform a deeper merge, recursively merge object properties and arrays.

See the documentation on the Lodash documentation.

Download mine for freeJavaScript beginner's manual


More js tutorials: