一、面对的一个开发场景是,在开发过程中遇到收集到的用户表单数据都是中文,需要将中文处理成英文,然后传递给后端,那么如何操作呢?
1、首先需要准备好处理的数据的字段
const mapInfo = {
入职日期: 'timeOfEntry',
手机号: 'mobile',
姓名: 'username',
转正日期: 'correctionTime',
工号: 'workNumber',
部门: 'departmentName',
聘用形式: 'formOfEmployment'
}
2、然后就是使用遍历的方法将数据拿取转换,具体代码如下:
async handleSuccess({ results, header }) {
const mapInfo = {
入职日期: 'timeOfEntry',
手机号: 'mobile',
姓名: 'username',
转正日期: 'correctionTime',
工号: 'workNumber',
部门: 'departmentName',
聘用形式: 'formOfEmployment'
}
// 循环所有的列表参数对象
var newResults = results.map((item) => {
// 定义一个空对象
var obj = {}
// 获取中文的数组
var chkeys = Object.keys(mapInfo)
// 循环遍历数组中的每一个数据
chkeys.forEach((key) => {
// 获取英文按键
var enKey = mapInfo[key]
/* 4-重新定义数组中每一项的值 */
/* 5-解决excel时间转换问题 formatExcelDate */
if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
obj[enKey] = new Date(formatExcelDate(item[key]))
} else {
obj[enKey] = item[key]
}
})
return obj
})
console.log(newResults, 455)
// eslint-disable-next-line no-unused-vars
const res = await importEmployee(newResults)
}
3、其中map和forEache的相同点是:
- 都是数组的方法
- 都用来遍历数组
- 两个函数都有4个参数:匿名函数中可传3个参数item(当前项), index(当前项的索引), arr(原数组),还有一个可选参数this
- 匿名函数中的this默认是指向window的
- 对空数组不会调用回调函数
- 不会改变原数组(某些情况下可改变) 不同点: 1.map是创建一个新的数组,并且有返回值,不能改变原数组的值,而forEach没有返回值,可改变原数组的情况。
二、第一个map是将前面展示的3个对象全部都遍历一遍,第二个就是准备获取中文数组,将数组中的每一项都遍历出来,然后进行中英文的转换,其中遇到的excel的事件转换的问题(也就是部分数据显示452717年),需要使用js和excel时间转换来解决:
/* js和excel时间转换 */
export function formatExcelDate(numb, format = '/') {
const time = new Date(
(numb - 25567) * 24 * 3600000 -
5 * 60 * 1000 -
43 * 1000 -
24 * 3600000 -
8 * 3600000
)
time.setYear(time.getFullYear())
const year = time.getFullYear() + ''
const month = time.getMonth() + 1 + ''
const date = time.getDate() + ''
if (format && format.length === 1) {
return year + format + month + format + date
}
return (
year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
)
}