javascript - 如何将对象对象的对象解构为对象的对象?
问题描述
我让我们说这个对象
const obj = {
background: {
backgroundColor:{
background: '#ffffff'
},
backgroundImage:{
background: 'url(...)'
}
},
header:{
logo:{
width: '100%'
},
title:{
color: '#000000'
}
}
}
我需要把它解构成这样:
const deconstructedObj = {
backgroundColor:{
background: '#ffffff'
},
backgroundImage:{
background: 'url(...)'
},
logo:{
width: '100%'
},
title:{
color: '#000000'
}
}
这只是一个例子,我的对象更大,但想法是一样的,第一个键需要解构,我该怎么做?
解决方案
这将使您到达那里,因为您只需要外部对象的值。Object.values会将这些内部对象抓取到一个可迭代数组中,而array.reduce()将帮助将它们全部连接成一个对象结果
Object.values(obj).reduce( (b,a) => ({...b, ...a}),{})
const obj = {
background: {
backgroundColor: {
background: '#ffffff'
},
backgroundImage: {
background: 'url(...)'
}
},
header: {
logo: {
width: '100%'
},
title: {
color: '#000000'
}
}
}
const decon = Object.values(obj).reduce( (b,a) => ({...b, ...a}),{})
console.log(decon)
推荐阅读
- authentication - 如何配置 Tomcat 领域超时
- visual-studio-code - 我如何必须设置更漂亮才能为我的所有项目工作,但要为我不单独工作的特定项目进行自定义设置?
- python - 如何仅在 numpy 数组的“一维”上应用 K-means++ 并按原样保留另一维
- python - 基于 Keras LSTM 的神经网络不学习
- elixir - 如何在 Elixir 中展平嵌套列表?
- android - 如何在android的表格布局中删除选定的行
- javascript - Google Apps 脚本解析 .txt 文件并将内容插入工作表?
- kubernetes-helm - 从值生成发布名称
- python - 如果python中的行总和为零,则用字符串替换单元格
- karate - 我正在尝试复制具有的 csv 文件的导入;作为空手道中的分隔符,但好像该工具不认为这是有效的