JS将数组转化为对象结构

99 阅读1分钟

将试将高维数组[1, 2, [3, [4, 5], 6], 7, [8], 9]变为如下结构:

{
  children:[
    {value:1},
    {value:2},
    {children:[
        {value:3},
          {children:[
            {value:4},
            {value:5}
          ]
        },
        {value:6}
      ]
    },
    {value:7},
    { children:[
        {value:8}
      ]
    },
    {value:9}
 ]
}

解法一:运用递归思想求解

function fn(arr){

    if(Array.isArray(arr)){
        return {children:convert(arr)}
    }else if(typeof arr == 'number'){
        return {value:arr}
    }
    
    function convert(arr){
        let result = [];
        for(let i=0;i<arr.length;i++){
            if(typeof arr[i] == 'number'){
                result.push({value:arr[i]});
            }else if(Array.isArray(arr[i])){
                result.push({children:convert(arr[i])});
            }
        }
        return result;
    }
}

解法二:运用JavaScript中的map思想求解。
map方法:对数组每一项都运行传入的函数,返回由每次函数调用的结果构成的数组

function fn(item){

    if(typeof item == 'number'){
        return {value:item}
    }else if(Array.isArray(item)){
        return {children:item.map(e=>fn(e))};
    }
}