Javascript note

字符串平铺对象属性转换成树状对象

问题描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
'A': 1,
'B.A': 2,
'B.B': 3,
'CC.D.E': 4,
'CC.D.F': 5
};
--------------转换成----------------------
{
'A': 1,
'B': {
'A': 2,
'B': 3
},
'CC': {
'D': {
'E': 4,
'F': 5
}
}
}


实现代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
objTransferTreeObj ( targetObj = null){
let result = {};
let tmpl = {};
Object.keys(targetObj).forEach((item,index)=>{
let temp = item.split('.');
tmpl = result
temp.map((prop,index)=>{
if( tmpl[prop]){
tmpl = tmpl[prop];
}else{
if(index === temp.length-1){
tmpl[prop] = targetObj[item]
}else{
tmpl[prop] = {};
}
tmpl = tmpl[prop];
}
})
})
console.log(result)
}