expandCommaKeyObject
展开对象中逗号分隔的键值对
引入版本
0.15.0
Demo
ts
import { expandCommaKeyObject } from '@wyfex/iutils'
/**
* ================== 1. 顶层逗号键 ==================
*/
const case1 = {
'name,age': ['张三', 18],
sex: '男'
}
console.log(expandCommaKeyObject(case1))
// { name: '张三', age: 18, sex: '男' }
/**
* ================== 2. 嵌套对象内部逗号键 ==================
*/
const case2 = {
user: {
'username,avatar': ['admin', 'https://xxx.png']
}
}
console.log(JSON.stringify(expandCommaKeyObject(case2), null, 2))
/*
{
user: { username: 'admin', avatar: 'https://xxx.png' }
}
*/
/**
* ================== 3. 多层深度嵌套 ==================
*/
const case3 = {
a: {
b: {
'x,y,z': [10, 20, 30]
}
}
}
console.log(JSON.stringify(expandCommaKeyObject(case3), null, 2))
/*
{
a: { b: { x: 10, y: 20, z: 30 } }
}
*/
/**
* ================== 4. 多层混合多个逗号键 ==================
*/
const case4 = {
'id,phone': [1, '13800138000'],
info: {
'province,city': ['四川', '宜宾'],
extra: {
'label,value': ['启用', 1]
}
}
}
console.log(JSON.stringify(expandCommaKeyObject(case4), null, 2))
/*
{
id: 1,
phone: '13800138000',
info: {
province: '四川',
city: '宜宾',
extra: { label: '启用', value: 1 }
}
}
*/
/**
* ================== 5. 逗号键对应非数组,不处理 ==================
*/
const case5 = {
'title,desc': '文本',
inner: { 'a,b': null }
}
console.log(JSON.stringify(expandCommaKeyObject(case5), null, 2))
// 原样保留原逗号key
/**
* ================== 6. 数组长度与key数量不匹配 ==================
*/
const case6 = {
'm,n': [1],
sub: { 'x,y': [1, 2, 3] }
}
console.log(JSON.stringify(expandCommaKeyObject(case6), null, 2))
// { m: 1, n: undefined, sub: { x: 1, y: 2 } }
/**
* ================== 7. 空对象 ==================
*/
console.log(expandCommaKeyObject({})) // {}
/**
* ================== 8. 无逗号键,原样返回 ==================
*/
const case8 = { a: 1, b: { c: 2 } }
console.log(JSON.stringify(expandCommaKeyObject(case8), null, 2))
/**
* ================== 9. 非法入参 ==================
*/
console.log(expandCommaKeyObject(null))
console.log(expandCommaKeyObject(undefined))
console.log(expandCommaKeyObject(123))
console.log(expandCommaKeyObject([]))
console.log(expandCommaKeyObject('abc'))
// 全部返回 {}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
99
100
101
102
103
104
105
106
107
108
109
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
99
100
101
102
103
104
105
106
107
108
109