如何将对象数组中YYYY-MM-DD格式字符串转为时间戳
问题:将数组中日期字符串转为时间戳
我有如下数组,每个对象的category是YYYY-MM-DD格式的字符串:
let originalData = [ { "category": "2017-07-24", "total": 1, "Col 1": 200 }, { "category": "2018-07-10", "total": 1, "Col 1": 100 }, { "category": "2018-11-12", "total": 1, "Col 1": 101 }, { "category": "2019-08-11", "total": 1, "Col 1": 153 }, { "category": "2019-09-11", "total": 1, "Col 1": 198 } ]
需要转换成每个对象的category为对应日期的时间戳,结果如下:
let desiredResult = [ { "category": new Date(2017, 7, 24).getTime(), "total": 1, "Col 1": 200 }, { "category": new Date(2018, 7, 10).getTime(), "total": 1, "Col 1": 100 }, { "category": new Date(2018, 11, 12).getTime(), "total": 1, "Col 1": 101 }, { "category": new Date(2019, 8, 11).getTime(), "total": 1, "Col 1": 153 }, { "category": new Date(2019, 9, 11).getTime(), "total": 1, "Col 1": 198 } ]
注意:原始category里的月份、日期带前导0(比如"2017-07-24"的月份是07),但new Date(2017, 07, 24)不能正常工作,必须用不带前导0的数字(比如7)。我知道可以用forEach遍历处理,但不知道怎么去掉前导0。
解决方案
可以通过以下几种简单方法实现:
方法1:拆分字符串转数字
利用字符串的split方法拆分日期,再通过+号自动将带前导0的字符串转为数字(自动去除前导0):
originalData.forEach(item => { // 拆分日期字符串为年、月、日三部分 const [year, month, day] = item.category.split('-'); // 转成数字后传入Date构造函数,再取时间戳 item.category = new Date(+year, +month, +day).getTime(); });
方法2:使用正则提取
如果担心拆分的格式问题,也可以用正则匹配年、月、日,再转数字:
originalData.forEach(item => { const matchResult = item.category.match(/^(\d{4})-(\d{2})-(\d{2})$/); if (matchResult) { const year = +matchResult[1]; const month = +matchResult[2]; const day = +matchResult[3]; item.category = new Date(year, month, day).getTime(); } });
方法3:创建新数组(不修改原数组)
如果不想修改原数组,可以用map生成新数组:
const desiredResult = originalData.map(item => ({ ...item, category: (() => { const [year, month, day] = item.category.split('-'); return new Date(+year, +month, +day).getTime(); })() }));
说明:+号在这里的作用是将字符串类型的年、月、日转为数字,带前导0的字符串(比如"07")转成数字后会自动变成7,刚好符合需求。
内容的提问来源于stack exchange,提问作者Beginner_Hello
相关产品推荐
相关产品推荐

