在映射对象中添加自定义键值时月份转换函数返回undefined的问题
问题排查与修复方案
我帮你梳理了下导致月份字段返回undefined的几个核心问题,咱们一步步来修复:
1. CSV字段名与代码引用不匹配
你的CSV表头是index(小写i)、Limit(大写L),但代码里却用了错误的字段名:
item['?Index']:多了个问号且大小写不对,应该改成item['index']item['limit']:表头是大写L的Limit,所以要改成item['Limit']
字段名不匹配会导致后续逻辑取不到正确值,甚至间接影响月份转换的输入有效性。
2. 月份索引偏移+类型问题
你的日期格式是DD/MM/YYYY,比如01/05/2020,split('/')[1]得到的是字符串类型的'05',而你的monthNames数组是从索引0对应1月(Jan):
- 直接用字符串数字作为数组索引可能存在隐式转换问题
- 未做减1操作会导致索引偏移(比如5月对应索引4,你用5会取到6月的
Jun,12月则超出数组范围返回undefined)
修改月份获取逻辑:
let month = parseInt(item['Date'].split('/')[1], 10) - 1; // 转数字后减1,匹配数组正确索引
同时优化转换函数,增加异常处理避免无效输入:
const monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]; const convertNumberToMonth = (number) => { // 处理非数字、NaN、超出0-11范围的无效输入 if (typeof number !== 'number' || isNaN(number) || number < 0 || number > 11) { return 'Unknown'; // 可替换为你需要的默认值 } return monthNames[number]; }; module.exports = convertNumberToMonth;
3. fs.writeFileSync的错误用法
fs.writeFileSync是同步方法,不支持回调函数,你写的回调参数无效,错误处理应该用try/catch包裹:
try { fs.writeFileSync('output.json', JSON.stringify(newArrayOfObj), 'utf-8'); console.log('Data successfully loaded!'); } catch (err) { console.error('Failed to write file:', err); }
修复后的完整代码
const csvtojson = require('csvtojson'); const fs = require('fs'); const convertNumberToMonth = require('./your-helper-file-path'); // 替换为你的助手文件实际路径 csvtojson() .fromFile('Data.csv') .then((json) => { const newArrayOfObj = json.map((item) => { let month = parseInt(item['Date'].split('/')[1], 10) - 1; return { indessx: item['index'], // 修正字段名 type: item['origin'], number: item['Limit'], // 修正字段名 month: convertNumberToMonth(month), date: item['Date'], }; }); try { fs.writeFileSync('output.json', JSON.stringify(newArrayOfObj), 'utf-8'); console.log('Data successfully loaded!'); } catch (err) { console.error('Error writing output file:', err); } }) .catch((err) => { console.error('Error parsing CSV:', err); });
这样修改后,月份字段就能正确显示对应的月份缩写,同时也修复了其他潜在的bug。
内容的提问来源于stack exchange,提问作者Rishav Sinha
相关产品推荐
相关产品推荐

