有更好的方法或者代码优化,欢迎码友留言交流、讨论!
我是将方法均放在class类里面
class Utils {
Function () {}
......
}
export default new Utils()
以下方法均为自己开发项目时经常用到的,方便快捷
一、数组常用方法
/**
* array-数组对象排序方法
* @param {*} data 数据
* @param {*} property 排序字段
* @param {*} order 顺序
*/
compareSort(data = [], property: string, order = 'asc') {
if (data.length === 0 || !property) return []
return data.sort(function (a: any, b: any) {
const value1: any = a[property]
const value2: any = b[property]
// 判断是否可以是有限数值
if (isFinite(value1) && isFinite(value2)) {
return order === 'asc'
? Number(value1) > Number(value2)
? 1
: -1
: Number(value1) > Number(value2)
? -1
: 1
} else {
return order === 'asc'
? value1.localeCompare(value2)
: value2.localeCompare(value1)
}
})
}
/**
* array-数组对象分组方法
* @param {*} data 数据
* @param {*} property 分组字段
* @param {*} isArray 是否转换为数组
* @param {*} fields 需要处理的字段数组[['新的字段', '原始字段'],['新的字段', '原始字段']]
*/
groupByfield(data = [], property: string, isArray = true, fields = []) {
if (data.length === 0 || !property) return data
data = JSON.parse(JSON.stringify(data))
const newObj: any = data.reduce((obj: any, item: any) => {
// 处理字段
fields.map((arr) => {
item[arr[0]] = item[arr[1]] || null
})
// 处理分组
if (!obj[item[property]]) {
obj[item[property]] = {
name: item[property],
count: 1,
list: [item]
}
} else {
obj[item[property]].list.push(item)
obj[item[property]].count++
}
return obj
}, {})
return isArray ? Object.values(newObj) : newObj
}
/**
* array-数组对象累加方法
* @param {*} data 数据
* @param {*} property 累加字段字段,可单个可数组多个字段
* @param {*} point 小数点几位
*/
computedTotal(data = [], property = [], point = 0) {
if (data.length === 0 || !property) return data
return data
.reduce((total, item) => {
if (typeof property === 'string') {
return total + parseFloat(item[property] || 0)
} else {
return total + property.reduce((all, field) => all + parseFloat(item[field] || 0), 0)
}
}, 0)
.toFixed(point)
}
/**
* 复合数据数组指定属性去重,可根据某个字段或者多个字段去重
*@param {Array} data 数据
*@param {string | string[]} fields 字段
*/
uniqueData(data, fields = []) {
data = data ?? []
if (typeof fields === 'string') {
fields = [fields]
}
const res = new Map()
return data.filter((item) => {
// 多个字段值拼接起来作为key
const key = fields.reduce((value, fie) => value + item[fie], '')
return !res.has(key) && res.set(key, 1)
})
}
/**
* array-将key/value对象转换为数组
*@param {Array} data 数据对象
*@param {key} nameField 名称字段
*@param {value} valueField 值字段
*/
handleObjToArray(data = {}, nameField = 'name', valueField = 'value') {
const list: Array<any> = []
for (const [key, val] of Object.entries(data)) {
list.push({
[nameField]: key,
[valueField]: val
})
}
return list
}
二、echarts常用方法
/**
* echarts-处理分类多数组数据格式
* 提示:前提是每组数组里面的字段全都一样,且每个对象都只有两个字段,一个名称和一个值
* @param {Array} data 数据
* @param {Object} configs 配置,name: 数据中对应的名称字段,value:数据中对应的值字段,nameFormatter名称的处理方法
* {type1: [{name:'', value:''},{name:'', value:''}], type2: [{},{}]} 格式
*/
handleGroupToArray(data: object, configs = {}) {
if (!data) return
const list: any[] = []
const config = {
name: '',
value: '',
nameFormatter: '{n}', // 名字格式化'xxxx{n}xxxx'
...configs
}
for (const [key, item] of Object.entries(data)) {
item.map((li: any) => {
const isname = list.find(
(fie) =>
fie.name === config.nameFormatter.replace('{n}', li[config.name])
)
if (isname) {
isname[key] = li[config.value]
} else {
list.push({
name: config.nameFormatter.replace('{n}', li[config.name]),
[key]: li[config.value],
...li
})
}
})
}
return list
}
/**
* echarts-获取Y轴间隔及其最大最小值,此方法不完美,更完美的方法些许麻烦,不想去抠脑壳了
* @param {*数组对象[{}]} data
* @param {Array[]} fields ,需要计算值得字段数组
*/
getYaxisMaxMin(data = [], fields = []) {
if (!data || data.length === 0 || fields.length < 1) return
// 获取数据对象所有需要渲染的Y轴值
const list: any[] = []
data.map((item) => {
fields.forEach((fie) => {
if (item[fie]) list.push(parseInt(item[fie]))
})
})
// 最大值和最小值
const arrMax = Math.max(...list)
const arrMin = Math.min(...list)
// 计算取整得最大最小值
const maxmult = Math.pow(10, arrMax.toString().length - 1 || 1)
const minmult = Math.pow(10, Math.abs(arrMin).toString().length - 1 || 1)
return {
max: Math.ceil(arrMax / maxmult) * maxmult,
min: Math.floor(arrMin / minmult) * minmult
}
}
三、el-table方法
/**
* table-处理多个字段相同数据(合并行单元格),为了计算表格需要合并的项
* @param {*数据} data ,默认[]
* @param {*需要处理的字段名} propertys
* 返回一个字段组成的对象{key: [1:5, 2:0, 3:6, 4:0, 5: 0], key: []}
* 其中key为字段名,12345代表行数
* 用法:
* // 需要合并的字段,提示:需要按照字段展示顺序
const mergeFields: string[] = ['zq_name', 'dw_name'],
// 处理的需要合并表格数据
let mergeData:any = {}
// 得到合并数据
mergeData = $utils.computedFileList(tableData, mergeFields)
// 处理合并行
spanMethod ({ column, rowIndex }) {
if (mergeFields.indexOf(column.property) !== -1) {
if (mergeData[column.property]) {
if (mergeData[column.property][rowIndex]) {
return {
rowspan: mergeData[column.property][rowIndex],
colspan: 1
}
} else {
return {
rowspan: 0,
colspan: 0
}
}
}
}
}
*/
computedFileList(data = [], propertys = []) {
if (propertys.length < 1 || data.length < 1) return {}
return propertys.reduce((obj: any, key: string) => {
obj[key] = []
let numerical = 0
// 循环当前字段所有行数据,取出相同行的数量,并储存下来,相同多少行就合并多少行
data.map((item: any, itemindex: number) => {
// 如果所有列的上下两行字段都一样,则需要合并,数量+1
if (itemindex !== 0 && item[key] === data[itemindex - 1][key]) {
obj[key][numerical] += 1
obj[key].push(0)
} else {
numerical = itemindex
obj[key].push(1)
}
})
return obj
}, {})
}
四、号码验证、base64加密,数字千分位
// 正则判断号码是否正确
isCallPhone(val) {
// 验证手机号的正则表达式
const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/.test(val)
const regTel = /^([0-9]{3,4}-)?[0-9]{5,8}$/.test(val)
if (regMobile || regTel) {
return true
} else {
return false
}
}
// base64加密
encrypt(value) {
let typeValue = typeof value
if (typeValue == 'string' || typeValue == 'number') {
return window.btoa(
window.encodeURIComponent(value).replace(/%([0-9A-F]{2})/g, function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1)
})
)
} else {
return value
}
}
/**
* // 处理数字是否需要千分位
* @param {值} value
* @param {是否需要逗号千分位} isComma
* @param {保留位数} fixed
*/
numberComma(value, isComma = true, fixed = 2) {
if (!value) return ''
// 统一先处理小数保留位数
const number = Number(value.toString().replaceAll(',', '')).toFixed(fixed)
if (isComma) {
let cnum = number.split('.')
// 整数部分
const int = cnum[0].includes(',') ? cnum[0] : cnum[0].replace(/(?!^)(?=(?:\d{3})+$)/g, ',')
return int + (cnum[1] ? `.${cnum[1]}` : '')
} else {
return number
}
}
五、树结构递归相关方法
相关方法放在了另一篇文章中 树结构处理方法