首页 > 解决方案 > 使用开始时间和结束时间将对象数组拆分为一小时跨度组?

问题描述

我需要将对象数组拆分为

{
  start_time: "2021-08-23T04:40:59.000Z",
  end_time : "2021-08-23T04:41:34.000Z",
  data: 'Some data' // not relevant
 }

根据开始时间和结束时间,按 1 小时跨度的块,小时开始,例如:10.00 - 11.00、11.00 - 12.00 等。

这是我想出的,但它的结果只有一次开始或结束:

const createRangeKey = (end_time) => {
  const hour = new Date(end_time).getHours(); // get the hour
  const start = hour - (hour % 1); // normalize to the closest even hour

  return `${start}-${start + 1}`; // get the key
};

const result = data.reduce((r, o) => {
  const key = createRangeKey(o.end_time); // get the key

  if (!r[key]) r[key] = []; // init if not existing on the object

  r[key].push(o); // add the object to the key

  return r;
}, {});

标签: javascript

解决方案


已编辑

注意:密钥将采用24 小时格式。

const testVals = {
  start_time: "2021-08-23T04:40:59.000Z",
  end_time : "2021-08-23T06:41:34.000Z",
  data: 'Some data' // not relevant
 }

const createRangeKey = (start_time) => {
    
    const hour = start_time.getHours()
    return `${hour}-${hour + 1}`; // get the key
  };



const getTimeSlots = ( start_time, time_gap) =>{
    const time_list = [start_time]
    const time_slots = []
    for(let i=0 ; i<time_gap ; i++){
    const next_time_slot = new Date(time_list[i])
    next_time_slot.setHours(next_time_slot.getHours() + 1)
    time_list.push(next_time_slot)
    const key = createRangeKey(time_list[i])
    time_slots.push(
      {
        [[key]]: {
          'start_time':time_list[i],
          'end_time':next_time_slot
        }
      }
    )
  }
  return time_slots
}
const result = () =>{
  
  const start_time = new Date(testVals.start_time)
  
  const end_time = new Date(testVals.end_time)
  
  const time_gap = (end_time - start_time) / (1000 * 60 * 60)
  
  const time_slots = getTimeSlots(start_time ,time_gap )
  return time_slots
  
}  

console.log(result())


推荐阅读