Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

js中多级对象转化问题

有什么比较简化的方法可以把如下对象:

 let obj =?{

 "a.c.d": 1,

 "e.d.w": 2

 }

转成:

{
 a:{
   c:?{
     d: 1
   }
 },

 e:{
   d:{
    w: 2
   }
 }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 var obj = {

 "a.c.d": 1,

 "e.d.w": 2

 }
 
 function restructObject(obj) {
   return Object.keys(obj).reduce((robj,propstr) => {
     
     propstr.split('.').reduce((res, prop, i, props) => {
       if(i == props.length-1) return res[prop] = obj[propstr];
       return res[prop] = {}
     }, robj);
     
     return robj
   }, {});
 }

restructObject(obj)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...