一、扁平转树形

var data=[
{pid:0,id:'a',value:'陕西'},
    {pid:'a',id:01,value:'西安'},
        {pid:01,id:301,value:'雁塔区'},
        {pid:01,id:302,value:'高新区'},
    {pid:'a',id:02,value:'渭南'},
    {pid:'a',id:03,value:'咸阳'},
{pid:0,id:'b',value:'广东'},
    {pid:'b',id:11,value:'广州'},
    {pid:'b',id:12,value:'深圳'},
    {pid:'b',id:13,value:'潮汕'},
{pid:0,id:'c',value:'湖南'},
    {pid:'c',id:21,value:'长沙'},
    {pid:'c',id:22,value:'常德'},
    {pid:'c',id:23,value:'岳阳'},
];
function toTree(data){
  let cloneData = JSON.parse(JSON.stringify(data))    // 对源数据深度克隆
  let tree = cloneData.filter((father)=>{              //循环所有项
        let branchArr = cloneData.filter((child)=>{
            return father.id == child.pid;//返回每一项的子级数组
        });
        if(branchArr.length>0){
            father.children = branchArr; //如果存在子级,则给父级添加一个children属性,并赋值
        }
        return father.pid==0;//返回第一层
    });
    return tree;    //返回树形数据
}
var tree=toTree(data);
console.log(tree);
//递归方法:
function toTree(data) {
    // 删除 所有 children,以防止多次调用
    data.forEach(function (item) {
        delete item.children;
    });
    // 将数据存储为 以 id 为 KEY 的 map 索引数据列
    var map = {};
    data.forEach(function (item) {
        map[item.id] = item;
    });
    var val = [];
    data.forEach(function (item) {
        // 以当前遍历项,的pid,去map对象中找到索引的id
        var parent = map[item.pid];
            // 好绕啊,如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中
            if (parent) {
                (parent.children || ( parent.children = [] )).push(item);
            } else {
                //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中,作为顶级
                val.push(item);
            }
        });
        return val;
}
    console.log(toTree(data))

二、树形转扁平

var data=[
    {id: "a",pid: 0,value: "陕西",children:[
        {id: 01,pid: "a",value: "西安"},
        {id: 02,pid: "a",value: "渭南"},
        {id: 03,pid: "a",value: "咸阳"},
    ]},
    {id: "b",pid: 0,value: "广东",children:[
        {id: 11,pid: "b",value: "广州"},
        {id: 12,pid: "b",value: "深圳"},
        {id: 13,pid: "b",value: "潮汕"},
    ]},
    {id: "c",pid: 0,value: "湖南",children:[
        {id: 21,pid: "c",value: "长沙"},
        {id: 22,pid: "c",value: "常德"},
        {id: 23,pid: "c",value: "岳阳"},
    ]},
];
function toLine(data){
    return data.reduce((arr, {id, value, pid, children = []}) =>
        arr.concat([{id, value, pid}], toLine(children)), [])
        return result;
}
var listarr=toLine(data);
console.log(listarr);
03-05 15:22