typescript - 转换对象中具有相同键的数组
问题描述
我有一个数组,我想将其转换为按相同键分组的对象(这只是一个数字)
let array = [
{"2": {
"5": {
"valore": "COLORE 1",
"obbligatorio": null
}
}
},
{"2": {
"20": {
"valore": "MATERIALE 2",
"obbligatorio": true
}
}
},
{"2": {
"21": {
"valore": "LUNGHEZZA 2",
"obbligatorio": true
}
}},
{"3": {"6": {"valore": "MATERIALE 4","obbligatorio": true}}}]
我的目的是在对象中转换数组并按相同的键进行分组,如下所示:
"2": {
"5": {
"valore": "COLORE 1",
"obbligatorio": null
},
"20": {
"valore": "LUNGHEZZA 2",
"obbligatorio": true
},
"21": {
"valore": "MATERIALE 3",
"obbligatorio": true
}
},
"3": {
"6": {
"valore": "MATERIALE 4",
"obbligatorio": true
}
}
问题是当我尝试转换时:
let obj = Object.assign({}, ...array);
它仅按两个值分组:
"2": {最后一个值} "3": {3的值}
我该如何解决这种行为?
解决方案
let array = [{
"2": {
"5": {
"valore": "COLORE 1",
"obbligatorio": null
}
}
},
{
"2": {
"20": {
"valore": "MATERIALE 2",
"obbligatorio": true
}
}
},
{
"2": {
"21": {
"valore": "LUNGHEZZA 2",
"obbligatorio": true
}
}
},
{
"3": {
"6": {
"valore": "MATERIALE 4",
"obbligatorio": true
}
}
}
]
const output = array.reduce((acc, val) => {
const key = Object.keys(val)[0]
if (!acc[key]) acc[key] = {}
acc[key] = { ...acc[key], ...val[key]}
return acc
}, {})
console.log(output)
推荐阅读
- android - Kotlin - Mockito 验证方法调用
- javascript - 如何修复加载超过 2 分钟的three.js 并且崩溃
- python - 迭代嵌套列表并计算特定值
- node.js - Node js错误处理它使服务器崩溃
- c# - 字符串中间的插值
- imagemagick - 如何根据尺寸和位深度计算 png 大小
- php - 从数据库中检索到的每个 php 输出都有一个按钮
- node.js - 如何防止在express.js中多次调用路由
- reactjs - 如何禁用 ListItem 的一些 Material UI css
- android - 单击持有人上的 itemView 时无法打开片段