编辑代码

//JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
//树形结构化

let source = [
    {
        id: 1,
        pid: 0,
        name: 'body'
    },
    {
        id: 2,
        pid: 1,
        name: 'title'
    },
    {
        id: 3,
        pid: 2,
        name: 'div'

    }
]

//将上面数据树形结构化

function jsonToTree(data) {
    let parents = data.filter(p => p.pid === 0),
        children = data.filter(c => c.pid !== 0);

        formatData(parents,children)

    function formatData(parents,children) {
        parents.map(p => {
            children.map((c, index) => {
                if (p.id == c.pid) {
                    let _c = JSON.parse(JSON.stringify(children))
                    _c.splice(index, 1)
                    formatData([c],_c)

                    if(p.children){
                        p.children.push(c)
                    }else{
                        p.children = [c]
                    }

                }
            })
        })
        
    }
    return parents
}

//console.log(jsonToTree(source))


//map
function mapToTree(data){
    let map = {}
    let result = []

    data.forEach(item => map[item.id] = item)
    
    data.forEach(item =>{
        //获取当前item的父节点
        let parent = map[item.pid]
        //如果父节点存在
        if(parent){
            if(parent.children){
                parent.children.push(item)
            }else{
                parent.children = [item]
            }

        }else{
            //父节点不存在,其实就是pid为0的根节点
            result.push(item)
        }
    })
    return result

}

console.log('map',mapToTree(source))