fur*_*ner 5 javascript javascript-objects
我想合并两个对象,覆盖属性,但保留未被覆盖的属性。
示例:我有以下对象
const theme = {
colors: {
base: '#fff',
accent: '#ff0000'
}
}
Run Code Online (Sandbox Code Playgroud)
和
const themeOverride = {
colors: {
accent: '#ff8900'
}
}
Run Code Online (Sandbox Code Playgroud)
并希望将它们合并在一起
const newTheme = {
colors: {
base: '#fff',
accent: '#ff8900'
}
}
Run Code Online (Sandbox Code Playgroud)
如果只想合并theme和themeOverride的属性颜色,则可以通过以下代码完成:
var theme = {
colors: {
base: '#fff',
accent: '#ff0000'
}
};
var themeOverride = {
colors: {
accent: '#ff8900'
}
};
Object.assign(theme.colors, themeOverride.colors);
console.log(theme);Run Code Online (Sandbox Code Playgroud)
您可以使用Object.assign来合并这些对象
更新现有对象
const theme = {
colors: {
base: '#fff',
accent: '#ff0000'
}
}
const themeOverride = {
colors: {
accent: '#ff8900'
}
}
Object.assign(theme.colors, themeOverride.colors)
console.log(theme)Run Code Online (Sandbox Code Playgroud)
或者创建新对象
const theme = {
colors: {
base: '#fff',
accent: '#ff0000'
}
}
const themeOverride = {
colors: {
accent: '#ff8900'
}
}
newTheme = { colors: Object.assign({}, theme.colors, themeOverride.colors) }
console.log(newTheme)Run Code Online (Sandbox Code Playgroud)
JS 没有内置的方法来执行此操作,但使用 Lodash、Underscore_.merge()或 Ramda来实现这一点非常简单_.mergeDeepLeft(),所有这些都递归地合并对象。
const theme = {
colors: {
base: '#fff',
accent: '#ff0000'
}
}
const themeOverride = {
colors: {
accent: '#ff8900'
}
}
const newTheme = _.merge(theme, themeOverride);
console.log(newTheme);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>Run Code Online (Sandbox Code Playgroud)