Everybody is good! My name is Dai Xiangtian

QQ group: 602504799

If do not understand, can add QQ group consulting understanding

// source data string const STR = 'A.B.C.D '; // split and reverse const arr = str.split('.').reverse(); // Create a new object to accept const data = {}; // Give the default value data[arr[0]] = 1; Const res = arr.reduce((obj,key,index)=>{// Omit the first key if(! index){ return obj }; Const lastKey = arr[index-1]; // get the lastKey const lastKey = arr[index-1]; Obj [key] = {}; Obj [key][lastKey] = obj[lastKey]; obj[lastKey] = obj[lastKey] Delete obj[lastKey] // return obj; }, {... data}); // The es6 extension operator is used here to prevent the source data from being changed // output console.log(res);Copy the code

encapsulation

Function strToObject(STR, defaultValue = null){const arr = str.split('.').reverse(); // Create a new object to accept const data = {}; Data [arr[0]] = defaultValue; Return arr.reduce((obj,key,index)=>{// omit the first key if(! index){ return obj }; Const lastKey = arr[index-1]; // get the lastKey const lastKey = arr[index-1]; Obj [key] = {}; Obj [key][lastKey] = obj[lastKey]; obj[lastKey] = obj[lastKey] Delete obj[lastKey] // return obj; }, {... data}); // The es6 extension operator is used to prevent the source data from being changed.Copy the code