-
Notifications
You must be signed in to change notification settings - Fork 0
/
连续字符串转换成对象.js
40 lines (35 loc) · 892 Bytes
/
连续字符串转换成对象.js
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
function strToObj(value, obj, keys) {
let current = obj;
keys.forEach((key, index) => {
if (!current[key]) {
current[key] = index === keys.length - 1 ? value : {}
}
current = current[key]
})
}
function strToArray(value, obj, keys) {
let current = obj;
keys.forEach((key, index) => {
if (!current[key]) {
current[key] = index === keys.length - 1 ? { [key]: value } : []
}
current = current[key]
})
}
const testData = {
"a.b.c": "hello",
"a.b.e": "你好",
"a.0.0.m": "nihao"
}
const str = Object.keys(testData)
const obj = {}
str.forEach(str => {
const hasNumber = /\d/.test(str)
const keys = str.split('.')
if (hasNumber) {
strToArray(testData[str], obj, keys)
} else {
strToObj(testData[str], obj, keys)
}
})
console.log(JSON.stringify(obj))