Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two objects with override in javascript [duplicate]

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'
  }
}
like image 539
furtner Avatar asked Nov 21 '17 10:11

furtner


2 Answers

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);
like image 139
Faly Avatar answered Nov 10 '22 00:11

Faly


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)
like image 23
Mikhail Katrin Avatar answered Nov 09 '22 23:11

Mikhail Katrin