One data grid for JavaScript, React, Vue & Angular. Sorting, filtering, virtualization, pinning, and CSV export included. Early access $199 $349 → [Get it now]

How to Merge Two Objects in JavaScript

As the creator of CoreUI, I’ll demonstrate the most effective methods to merge objects in JavaScript.

You can merge objects in JavaScript using the spread operator (...) or Object.assign() method, with spread operator being the modern preferred approach.

// Merging with spread operator (preferred)
const obj1 = { name: 'John', age: 30 }
const obj2 = { city: 'New York', country: 'USA' }
const merged = { ...obj1, ...obj2 }

// Merging with Object.assign
const mergedAssign = Object.assign({}, obj1, obj2)

// Merging with property override
const obj3 = { name: 'Jane', age: 30 }
const obj4 = { name: 'John', city: 'Boston' }
const overridden = { ...obj3, ...obj4 } // name becomes 'John'

// Conditional merging
const conditionalMerge = {
  ...obj1,
  ...(obj2.city && { city: obj2.city })
}

The spread operator creates a new object by expanding properties from source objects. Properties from objects listed later override those from earlier objects. Object.assign() works similarly but modifies the first argument (use empty object {} as target to avoid mutation). For deep merging of nested objects, you’ll need specialized libraries like Lodash’s merge() function or implement custom recursive merging logic.

Best Practice Note:

In CoreUI projects, we extensively use object merging for component configuration and theme customization. The spread operator is ideal for merging component props with default settings, ensuring clean and predictable component behavior across your application.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Redirect to a New URL Using JavaScript Redirect Techniques
How to Redirect to a New URL Using JavaScript Redirect Techniques

How to Achieve Perfectly Rounded Corners in CSS
How to Achieve Perfectly Rounded Corners in CSS

How to Add a Tab in HTML
How to Add a Tab in HTML

How to Open Link in a New Tab in HTML?
How to Open Link in a New Tab in HTML?