How to merge two objects in JavaScript

Merging objects is a common pattern when combining configuration options, updating state, or processing API responses. As the creator of CoreUI, a widely used open-source UI library, I’ve merged objects extensively for component configuration and theme customization. From my expertise, the most elegant and modern solution is using the spread operator to combine objects. This approach is clean, readable, and handles property overriding naturally.

Use the spread operator to merge two objects with later properties overriding earlier ones.

const obj1 = { name: 'John', age: 30 }
const obj2 = { age: 31, city: 'New York' }
const merged = { ...obj1, ...obj2 }

Here the spread operator expands both objects into a new object literal. When properties have the same key (like ‘age’), the rightmost object’s value takes precedence. The resulting merged object contains all properties from both objects: { name: 'John', age: 31, city: 'New York' }.

Best Practice Note:

This creates a shallow merge only. For deep merging nested objects, consider utility libraries like Lodash. This is the same approach we use in CoreUI for merging component props with default configurations.


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.

Answers by CoreUI Core Team