对称汇总算法

63 阅读1分钟

问题


let array = [0'a'1'b'2'c'3'e'2'd'1'x'0'ff'];
//求结果输出
{
      a: {
        b: {
          c: {
            enull
          },
          dnull
        },
        xnull
      },
      ffnull
    }

方案1 递归

let array = [0'a'1'b'2'c'3'e'2'd'1'x'0'ff'];

let obj = {}
find(obj,array)
console.log("obj=>",JSON.stringify(obj))
function find(inputObj){
    let len = array.length 
    let arr2 = array.splice(len-2,2) 
    let newObj2 = arrayToObj(inputObj,arr2,null) 
    let arr1 = array.splice(0,2)
    let newObj1 = arrayToObj(inputObj,arr1) 
    if(newObj1){
        find(newObj1)
    }
}
 
function arrayToObj(inputObj,inputArray,val = {}){
    if(inputArray == 0){
        return null
    }
    let newObj = val
    // console.log("inputArray[1]",inputArray[1]);
    inputObj[inputArray[1]] = newObj 
    return newObj
}

方案2 while循环

let array = [0'a'1'b'2'c'3'e'2'd'1'x'0'ff'];
let finalObj = {}
let nowObj = finalObj;
while (array.length > 0) {
    let [,lastKey] = array.splice(-2,2)
    let [,preKey] = array.splice(0,2)
    let newObj = {}
    if(preKey){
        nowObj[preKey] = newObj
    }
    if(lastKey){
        nowObj[lastKey] = null
    }
    nowObj = newObj
}
console.log("finalObj",JSON.stringify(finalObj));