javascript - 使用键拆分对象数组
问题描述
我有一个像下面这样的数据数组,需要通过使用带有开始和结束时间的 Value 属性来结构化
[{
"Timestamp": "2021-09-30T21:38:46.7000122Z",
"Value": "496",
},
{
"Timestamp": "2021-10-01T01:08:47.4690093Z",
"Value": "496",
},
{
"Timestamp": "2021-10-02T15:38:02.5080108Z",
"Value": "207",
},
{
"Timestamp": "2021-10-02T16:30:32.3410034Z",
"Value": "207",
},
{
"Timestamp": "2021-10-02T21:45:32.7460021Z",
"Value": "207",
},
{
"Timestamp": "2021-10-02T22:38:02.5839996Z",
"Value": "413",
},
{
"Timestamp": "2021-10-02T23:30:33.3980102Z",
"Value": "413",
},
{
"Timestamp": "2021-10-03T00:23:02.7130126Z",
"Value": "413",
},
{
"Timestamp": "2021-10-03T11:47:47.8630065Z",
"Value": "413",
}]
有没有办法将上面的数组组合成下面的格式,比如使用值的组,并选择第一个对象时间戳作为开始时间,最后一个对象时间戳值作为结束时间,如下所示
[{
"id": 496
"stTime": "2021-09-30T21:38:46.7000122Z"
"endTime": "2021-10-01T01:08:47.4690093Z"
},{
"id": 207
"stTime": "2021-10-02T15:38:02.5080108Z"
"endTime": "2021-10-02T21:45:32.7460021Z"
},{
"id": 413
"stTime": "2021-10-02T22:38:02.5839996Z"
"endTime": "2021-10-03T11:47:47.8630065Z"
}]
解决方案
您可以使用Object.values()提取Array.prototype.reduce()的值result
数组data
代码:
const data = [{Timestamp: '2021-09-30T21:38:46.7000122Z',Value: '496',},{Timestamp: '2021-10-01T01:08:47.4690093Z',Value: '496',},{Timestamp: '2021-10-02T15:38:02.5080108Z',Value: '207',},{Timestamp: '2021-10-02T16:30:32.3410034Z',Value: '207',},{Timestamp: '2021-10-02T21:45:32.7460021Z',Value: '207',},{Timestamp: '2021-10-02T22:38:02.5839996Z',Value: '413',},{Timestamp: '2021-10-02T23:30:33.3980102Z',Value: '413',},{Timestamp: '2021-10-03T00:23:02.7130126Z',Value: '413',},{Timestamp: '2021-10-03T11:47:47.8630065Z',Value: '413'}]
const result = Object
.values(
data.reduce((a, { Value, Timestamp }) => {
a[Value] = a[Value] || {
id: +Value,
stTime: Timestamp,
}
a[Value].endTime = Timestamp
return a
}, {})
)
console.log(result)
推荐阅读
- c++ - 使用 AV_PIX_FMT_D3D11 的 FFMPEG 从 NVENC 给出“注册输入资源时出错”
- github-actions - 如何使用 github 操作构建 xamarin android 应用程序?
- bash - bash 使用什么顺序来决定是使用别名、函数、内置还是可执行文件?
- math - 如何在SVG曲线上的每个点切线?
- python - 计算数据框列中间隔的标准偏差
- php - Apache 和 Nginx 之间的 PHP 服务器更改:3 倍的性能损失
- spring-boot - 在 Grails 4 中找不到 Http Session 复制的有效配置
- python - 提取路径的一部分
- java - 在 PostgreSQL 中使用 1 个查询选择特定行的最佳方法?
- wordpress - 如何在 WP 主题上解决此问题?