angular - 将数组转换为单个数组,并将键分配给对象值
问题描述
我有嵌套的对象格式,其中没有分配给值的键,格式如下所示:
{
"data": {
"2019": {
"January": {
"complaintRaised": 9,
"totalPending": 4,
"totalClosed": 0,
"resolvedPercent": 0
}
},
"2018": {
"May": {
"complaintRaised": 9,
"totalPending": 4,
"totalClosed": 0,
"resolvedPercent": 0
}
}
},
}
我需要将其转换为带有键的单个数组
response.data: [{
key: "2019"
"complaintRaised": 9,
"totalPending": 4,
"totalClosed": 0,
"resolvedPercent": 0
year: "2019-January"
},
{
key: "2018"
"complaintRaised": 9,
"totalPending": 4,
"totalClosed": 0,
"resolvedPercent": 0
year: "2018-May"
}
]
分配给值。
解决方案
如果同一年有超过一个月的时间,第一个答案将不起作用,如下例所示。此代码将处理所有月份。
const dataInput = {
"data": {
"2019": {
"January": {
"complaintRaised": 9,
"totalPending": 4,
"totalClosed": 0,
"resolvedPercent": 0
},
"March": {
"complaintRaised": 91,
"totalPending": 41,
"totalClosed": 10,
"resolvedPercent": 10
}
},
"2018": {
"May": {
"complaintRaised": 9,
"totalPending": 4,
"totalClosed": 0,
"resolvedPercent": 0
}
}
}
}
const response = {
data: Object.entries(dataInput.data).reduce((res, [year, val]) => ([
...res,
...Object.entries(val).reduce((res2, [month, val2]) => ([
...res2,
{
key: year,
...val2,
year: `${year}-${month}`
}
]), []),
]), [])
};
console.log(response);
推荐阅读
- python - 从 plotly 保存图像
- haskell - 函数的类型定义
- c# - 发送端口 Web HTTP 中的 BizTalk REST 获取方法
- bash - 在 gnu / linux 中,我如何将文件从初始字符串(foo)扫描到最终字符串(bar)
- python - Python 字节文字
- django - 删除设置为在表单集中删除的行并重复问题
- php - 带有两个按钮和 ajax 的 Sumbit 表单
- powershell - 将文件从父文件夹传输到多个子文件夹
- java - 如何为 Ondemand 触发器安排 Quartz Scheduler 作业?
- python - 为什么递归四分法比 C 和 python 中的迭代四分法更快?