首页 > 解决方案 > 使用键拆分对象数组

问题描述

我有一个像下面这样的数据数组,需要通过使用带有开始和结束时间的 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"
}]

标签: javascriptarrays

解决方案


您可以使用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)


推荐阅读