I want to merge two objects, override properties but keep properties that are not been overridden.
Example: I have the following Objects
const theme = {
colors: {
base: '#fff',
accent: '#ff0000'
}
}
and
const themeOverride = {
colors: {
accent: '#ff8900'
}
}
and would like to merge these together to get
const newTheme = {
colors: {
base: '#fff',
accent: '#ff8900'
}
}
If you just want to merge the property color of theme and themeOverride, you can do it by the code below:
var theme = {
colors: {
base: '#fff',
accent: '#ff0000'
}
};
var themeOverride = {
colors: {
accent: '#ff8900'
}
};
Object.assign(theme.colors, themeOverride.colors);
console.log(theme);
You can use Object.assign to merge these objects
Update existing object
const theme = {
colors: {
base: '#fff',
accent: '#ff0000'
}
}
const themeOverride = {
colors: {
accent: '#ff8900'
}
}
Object.assign(theme.colors, themeOverride.colors)
console.log(theme)
Or create new object
const theme = {
colors: {
base: '#fff',
accent: '#ff0000'
}
}
const themeOverride = {
colors: {
accent: '#ff8900'
}
}
newTheme = { colors: Object.assign({}, theme.colors, themeOverride.colors) }
console.log(newTheme)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With