You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何将扁平时间数组转换为按天合并的对象数组

JavaScript数组按天合并时间区间解决方案

原有代码问题说明

你之前使用固定步长为2的循环逻辑,默认每个日期后仅跟随1个时间区间,但实际示例中Tuesday、Wednesday后都跟随了多个时间区间,因此会把后续的时间项误判为新日期,最终出现数据错位、仅保留第一个时间区间的问题。

实现代码

核心逻辑为遍历数组时动态区分日期项和时间区间项:

  • 判定为日期项时,在结果数组中新增一条对象记录,同时记录当前正在处理的日期对象
  • 判定为时间区间项时,将内容追加到当前日期对象的time字段中
const ArrOfTime = ["Monday", "10:00-17:00", "Tuesday", "10:00-17:00", "17:00-21:00", "21:00-9:00", "Wednesday", "10:00-17:00", "17:00-21:00"]
const ArrOfObj = []
let currentDayItem = null

// 简易判断规则:时间区间带`-`,星期名称不带
for (const item of ArrOfTime) {
  if (!item.includes('-')) {
    // 遇到新日期,新建对象存入结果数组
    currentDayItem = {
      day: item,
      time: ''
    }
    ArrOfObj.push(currentDayItem)
  } else {
    // 遇到时间区间,追加到当前日期的time字段
    currentDayItem.time = currentDayItem.time ? `${currentDayItem.time}, ${item}` : item
  }
}

如果需要更严谨的判断,避免特殊无-的时间项导致异常,可以预先定义合法星期列表做校验:

const validWeekDays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
const ArrOfTime = ["Monday", "10:00-17:00", "Tuesday", "10:00-17:00", "17:00-21:00", "21:00-9:00", "Wednesday", "10:00-17:00", "17:00-21:00"]
const ArrOfObj = []
let currentDayItem = null

for (const item of ArrOfTime) {
  if (validWeekDays.includes(item)) {
    currentDayItem = {
      day: item,
      time: ''
    }
    ArrOfObj.push(currentDayItem)
  } else {
    currentDayItem.time = currentDayItem.time ? `${currentDayItem.time}, ${item}` : item
  }
}

以上两种写法运行后,ArrOfObj均符合你要求的目标格式。

内容的提问来源于stack exchange,提问作者LuAnBoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 10:27:04