How to merge properties of two JavaScript objects? (Object.assign, spread and other methods)
Hello everyone! I'm a beginner JS developer and I've encountered a problem. I have two objects with settings:
```javascript
const defaultSettings = {
theme: 'light',
fontSize: 14,
showSidebar: true
};
const userSettings = {
fontSize: 16,
showNotifications: true
};
```
I need to merge them so that the resulting object contains all properties from `defaultSettings`, but if `userSettings` has the same keys (e.g., `fontSize`), their values should override the default values. That is, I want to get:
```javascript
{
theme: 'light',
fontSize: 16, // overwritten from userSettings
showSidebar: true,
showNotifications: true // added from userSettings
}
```
I tried simply assigning: `const merged = { ...defaultSettings, ...use
No answers yet.
Log in to leave an answer