utils.ts
2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { excludeParseEventKeyList, excludeParseEventValueList } from '@/enums/eventEnum'
const tryRunFunction = (v: string) => {
try {
return eval(`(function(){return ${v}})()`)
} catch (error) {
return v
}
}
export const JSONParse = (data: string) => {
if (!data) return
return JSON.parse(data, (k, v) => {
// 过滤函数字符串
if (excludeParseEventKeyList.includes(k)) return v
// 过滤函数值表达式
if (typeof v === 'string') {
const someValue = excludeParseEventValueList.some(excludeValue => v.indexOf(excludeValue) > -1)
if (someValue) return v
}
// 还原函数值
if (typeof v === 'string' && v.indexOf && (v.indexOf('function') > -1 || v.indexOf('=>') > -1)) {
return tryRunFunction(v)
} else if (typeof v === 'string' && v.indexOf && v.indexOf('return ') > -1) {
const baseLeftIndex = v.indexOf('(')
if (baseLeftIndex > -1) {
const newFn = `function ${v.substring(baseLeftIndex)}`
return tryRunFunction(newFn)
}
}
return v
})
}
//解析web url 参数
export const parseWebUrl = (str = window.location.search) => {
const reg = /([^?&=]+)=([^&]+)/g
const params = {} as any
str.replace(reg, (_, k, v) => (params[k] = v))
return params
}
//嵌套对象转换为级联选择器数据格式
interface cascadingData {
label: string
value: string | cascadingData[] | number
children: cascadingData[] | null
}
export const convertToCascadingData = (obj: Recordable): cascadingData[] => {
const result: cascadingData[] = []
for (const key in obj) {
// eslint-disable-next-line no-prototype-builtins
if (obj.hasOwnProperty(key)) {
let value: cascadingData[] | string | number
if (typeof obj[key] === 'object' && obj[key] !== null) {
value = convertToCascadingData(obj[key])
} else {
value = String(obj[key])
}
result.push({
label: key,
value,
children: Array.isArray(value) ? value : null
})
}
}
return result
}
// 递归查找
export const findItemByLabel = (list:Recordable[], label:string) :Recordable | null => {
let res = list.find((item) => item.label == label) as Recordable | null;
if (res) {
return res;
} else {
for (let i = 0; i < list.length; i++) {
if (list[i].children instanceof Array && list[i].children.length > 0) {
res = findItemByLabel(list[i].children, label);
if (res) return res;
}
}
return null;
}
};