value.js
2.36 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* 通过路径获取值
* @param {Object} obj
* @param {String} path
* @param {Number} subIndex
* @returns
*/
export const getValueByPath = (obj, path, subIndex) => {
if (!obj || !path || path.constructor != String) {
return null
}
if (!/^\w?.*[\w|\]]$/.test(path)) {
return null
}
let pathAry = path.split('.')
if (pathAry.length == 1) {
return obj[path]
} else if (pathAry.length > 1) {
let ret = obj
for (var i = 0; i < pathAry.length; i++) {
const key = pathAry[i]
const match = /^(\w+)\[(\d+)\]$/.exec(key)
if (match) {
ret = ret[match[1]][match[2]]
} else if (ret && ret.constructor === Array) {
let index = 0
if (subIndex != null && subIndex != undefined) {
let preIndex = Number.parseInt(subIndex)
if (!isNaN(preIndex)) {
index = preIndex
}
}
ret = ret[index][key]
} else {
if (ret && ret[key]) {
ret = ret[key]
} else {
ret = null
}
}
}
return ret
}
return null
}
/**
* 通过路径设置对象中的属性
* @param {Object} obj
* @param {String} path
* @param {Any} value
* @param {Number} subIndex
* @returns
*/
export const setValueByPath = (obj, path, value, subIndex) => {
if (!obj || !path || path.constructor != String) {
return
}
if (!/^\w?.*[\w|\]]$/.test(path)) {
return
}
let pathAry = path.split('.')
if (pathAry.length == 1) {
obj[path] = value
} else if (pathAry.length > 1) {
let ret = obj
for (var i = 0; i < pathAry.length; i++) {
const key = pathAry[i]
const match = /^(\w+)\[(\d+)\]$/.exec(key)
if (i == pathAry.length - 1) {
if (match) {
ret[match[1]][match[2]] = value
} else if (ret && ret.constructor === Array) {
let index = 0
if (subIndex != null && subIndex != undefined) {
let preIndex = Number.parseInt(subIndex)
if (!isNaN(preIndex)) {
index = preIndex
}
}
ret[index][key] = value
} else {
if (ret && ret[key] !== undefined) {
ret[key] = value
} else {
ret = null
}
}
} else {
if (match) {
ret = ret[match[1]][match[2]]
} else {
ret = ret[key]
}
}
}
}
}