js实现无限层级树形数据结构(创新算法)

js实现无限层级树形数据结构(创新算法)

原始数据


let dataSource = [
    {
        id:1,
        pid:0,
        name:'一级菜单A'
    },
    {
        id:2,
        pid:0,
        name:'一级菜单B'
    },
    {
        id:3,
        pid:0,
        name:'一级菜单C'
    },
    {
        id:4,
        pid:1,
        name:'二级菜单A-A'
    },
    {
        id:5,
        pid:1,
        name:'二级菜单A-B'
    },
    {
        id:6,
        pid:2,
        name:'二级菜单B-B'
    },
    {
        id:7,
        pid:2,
        name:'二级菜单B-C'
    },
    {
        id:8,
        pid:6,
        name:'三级菜单B-B-A'
    },
    {
        id:9,
        pid:6,
        name:'三级菜单B-B-B'
    },
];

生成树型结构函数

function treeData(source, id, parentId, children){   
    let cloneData = JSON.parse(JSON.stringify(source))
    return cloneData.filter(father=>{
        let branchArr = cloneData.filter(child => father[id] == child[parentId]);
        branchArr.length>0 ? father[children] = branchArr : ''
        return father[parentId] == 0        // 如果第一层不是parentId=0,请自行修改
    })
}
 
// 调用时,字段名以字符串的形式传参,如treeData(source, 'id', 'parentId', 'children')

调用

let treeDataRes = treeData(dataSource,'id','pid','children');
console.log(treeDataRes);

使用nodejs输出到文件

var fs = require('fs')
// 第一个参数:文件路径
// 第二个参数:文件内容
// 第三个参数:回调函数
//    成功:
//      文件写入成功
//      error 是 null
//    失败:
//      文件写入失败
//      error 就是错误对象
fs.writeFile('./qwres.json', JSON.stringify(treeDataRes), function (error) {
  if (error) {
    console.log('写入失败')
  } else {
    console.log('写入成功了')
  }
});

查看结果

amazing

[
    {
        "id": 1,
        "pid": 0,
        "name": "一级菜单A",
        "children": [
            {
                "id": 4,
                "pid": 1,
                "name": "二级菜单A-A"
            },
            {
                "id": 5,
                "pid": 1,
                "name": "二级菜单A-B"
            }
        ]
    },
    {
        "id": 2,
        "pid": 0,
        "name": "一级菜单B",
        "children": [
            {
                "id": 6,
                "pid": 2,
                "name": "二级菜单B-B",
                "children": [
                    {
                        "id": 8,
                        "pid": 6,
                        "name": "三级菜单B-B-A"
                    },
                    {
                        "id": 9,
                        "pid": 6,
                        "name": "三级菜单B-B-B"
                    }
                ]
            },
            {
                "id": 7,
                "pid": 2,
                "name": "二级菜单B-C"
            }
        ]
    },
    {
        "id": 3,
        "pid": 0,
        "name": "一级菜单C"
    }
]

参考:https://blog.csdn.net/Mr_JavaScript/article/details/82817177

Last modification:June 24th, 2020 at 09:07 am
If you think my article is useful to you, please feel free to appreciate

Leave a Comment