javascript - 基于另一个对象数组创建对象数组
问题描述
尝试基于另一个对象数组创建对象数组。决定使用 flatmap 然后减少,但问题是当我在结果数组中有多个对象时 - 我无法在一个对象中收集多个状态。添加了我尝试过的内容以及我想要达到的结果。
是)我有的
const data = [
{
"timestamp": "2021-08-31T15:29:18Z",
"result": [
{
"label": "Not Covered",
"value": 132
}
]
},
{
"timestamp": "2021-09-30T15:29:18Z",
"result": [
{
"label": "Not Covered",
"value": 135
}
]
},
{
"timestamp": "2021-10-31T16:29:18Z",
"result": [
{
"label": "Not Covered",
"value": 135
}
]
}
]
我需要得到什么
[
{
"Not Covered":132,
"Active":0,
"Expiring Soon":0,
"timestamp": "2021-08-31T15:29:18Z"
},
{
"Not Covered":135,
"Active":0,
"Expiring Soon":0,
"timestamp": "2021-09-30T15:29:18Z"
},
{
"Not Covered":135,
"Active":0,
"Expiring Soon":0,
"timestamp": "2021-10-31T16:29:18Z"
}
]
我在做什么
let flattenedResult = data.flatMap(({result,...r}) => result.map(o => ({ ...o,...r})));
const chartData = flattenedResult.reduce((acc, item) => {
const {timestamp, value,label} = item;
acc.push({timestamp, "Not Covered":"Not Covered"===label?value:0,"Active":"Active"===label?value:0,"Expiring Soon":"Expiring Soon"===label?value:0});
return acc;
}, []);
我得到了什么:
[
{
"timestamp": "2021-08-31T15:29:18Z",
"Not Covered": 132,
"Active": 0,
"Expiring Soon": 0
},
{
"timestamp": "2021-09-30T15:29:18Z",
"Not Covered": 135,
"Active": 0,
"Expiring Soon": 0
},
{
"timestamp": "2021-10-31T16:29:18Z",
"Not Covered": 135,
"Active": 0,
"Expiring Soon": 0
}
]
解决方案
您还没有解释如何获得“活动”和“即将到期”的值,但我相信这样的事情应该会有所帮助
const data = [
{
"timestamp": "2021-08-31T15:29:18Z",
"result": [
{
"label": "Expiring Soon",
"value": 57
},
{
"label": "Not Covered",
"value": 132
},
{
"label": "Active",
"value": 42
}
]
},
{
"timestamp": "2021-09-30T15:29:18Z",
"result": [
{
"label": "Not Covered",
"value": 135
}
]
},
{
"timestamp": "2021-10-31T16:29:18Z",
"result": [
{
"label": "Not Covered",
"value": 135
},
{
"label": "Active",
"value": 42
}
]
}
];
console.log(data.reduce((acc, {timestamp, result}) => {
const datum = result.reduce((acc, {label, value}) => ({
...acc,
[label]: value,
}), {
timestamp,
'Not Covered': 0,
Active: 0,
'Expiring Soon': 0
});
return acc.concat(datum);
}, []));
推荐阅读
- string-matching - 使用 Oracle 进行模糊地址匹配
- ios - Flutter IOS Web Views - IOS 的 Webview 需要清晰
- groovy - BigDecimal 构造函数不接受支持的方法签名
- fullcalendar - 如何摆脱 fullcalendar.io 顶行滚动条?
- android - 如何从扫描的 BLE 设备中读取原始数据?
- ios - iOS Chrome 打开空白 PDF
- highcharts - 修复了 Highcharts 条之间的填充
- python - 检查输入任务的时间是否已过
- ionic-framework - 关于Ionic启动项目流程
- unity3d - Android Unity 设备上的 Websocket