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

JavaScript按指定年份格式化含年月数据的实现求助

实现摄像头数据的月份字段转换(JavaScript)

我来帮你完成这个数据转换的实现,先理清楚需求和现有代码的不足,再给出完整的解决方案:

需求回顾

你需要处理一组包含摄像头基础信息+各年份对应月份集合的JSON数据,结合给定的月份数字→英文缩写映射表,实现一个方法:

  • 根据用户选择的2015-2019区间内的年份
  • 转换每个摄像头数据:保留原有基础字段,同时添加12个以月份缩写命名的字段,存在对应月份则值为1,否则为0

示例参考

简化版输入

// 摄像头数据示例
const data = [
  {
    "camera_name": "Walls Demo",
    "camera_id": "CAM001",
    "years": {
      "2018": ["01", "03", "05"],
      "2019": ["02", "04"]
    }
  }
];

// 月份映射表
const months_chars = {
  "01": "jan", "02": "feb", "03": "mar", "04": "apr",
  "05": "may", "06": "jun", "07": "jul", "08": "aug",
  "09": "sep", "10": "oct", "11": "nov", "12": "dec"
};

输出(选择年份2018时)

{
  "camera_name": "Walls Demo",
  "camera_id": "CAM001",
  "jan": 1,
  "feb": 0,
  "mar": 1,
  "apr": 0,
  "may": 1,
  "jun": 0,
  "jul": 0,
  "aug": 0,
  "sep": 0,
  "oct": 0,
  "nov": 0,
  "dec": 0
}

现有代码的不足

你当前的片段只获取了目标年份对应的月份集合,但缺少三个关键步骤:

  • 保留摄像头的基础字段(如camera_name、camera_id)
  • 遍历所有月份映射,生成对应的12个字段并赋值
  • 将基础字段和月份字段合并为最终对象

完整实现代码

// 月份映射表(可直接复用你的现有定义)
const months_chars = {
  "01": "jan", "02": "feb", "03": "mar", "04": "apr",
  "05": "may", "06": "jun", "07": "jul", "08": "aug",
  "09": "sep", "10": "oct", "11": "nov", "12": "dec"
};

// 假设用户选中的年份(可替换为你的实际取值逻辑,比如从组件state/props获取)
const selectedYear = "2018";
// 可选:添加年份区间校验,确保在2015-2019之间
if (!["2015","2016","2017","2018","2019"].includes(selectedYear)) {
  throw new Error("年份需在2015-2019区间内");
}

// 核心转换方法
const formatCameraData = (cameraList, targetYear) => {
  return cameraList.map(camera => {
    // 1. 提取摄像头基础信息(排除原years字段)
    const { years, ...baseInfo } = camera;
    
    // 2. 获取当前年份对应的月份集合,无数据则设为空数组
    const presentMonths = years[targetYear] || [];
    
    // 3. 生成12个月份字段的键值对
    const monthFields = Object.entries(months_chars).reduce((acc, [monthNum, monthAbbr]) => {
      acc[monthAbbr] = presentMonths.includes(monthNum) ? 1 : 0;
      return acc;
    }, {});
    
    // 4. 合并基础信息和月份字段,返回最终对象
    return { ...baseInfo, ...monthFields };
  });
};

// 示例调用(替换为你的实际数据源)
const sampleCameraData = [
  {
    "camera_name": "Walls Demo",
    "camera_id": "CAM001",
    "years": {
      "2018": ["01", "03", "05"],
      "2019": ["02", "04"]
    }
  },
  {
    "camera_name": "Main Entrance",
    "camera_id": "CAM002",
    "years": {
      "2017": ["06", "07", "12"]
    }
  }
];

// 执行转换并打印结果
const formattedData = formatCameraData(sampleCameraData, selectedYear);
console.log(formattedData);

关键步骤解释

  1. 解构基础信息:用{ years, ...baseInfo }分离出摄像头的非年份字段,避免原years结构干扰结果
  2. 兼容无数据场景:如果目标年份不在摄像头的years中,默认用空数组,确保所有月份字段初始值为0
  3. 批量生成月份字段:通过Object.entries遍历映射表,用reduce构建每个月份缩写的键值对,通过includes判断是否存在对应月份
  4. 合并对象:用扩展运算符...将基础信息和月份字段合并,生成符合要求的最终结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:02:09