How to Merge Two Objects in JavaScript
As the creator of CoreUI and with over 25 years of JavaScript development experience, 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.



