关于javascript:将数组格式化为树型结构

43次阅读

共计 1296 个字符,预计需要花费 4 分钟才能阅读完成。

// 原始数据
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'},
];

/**
 * [将数组格式化为树型构造]
 * @param  {[type]} dataSource    [原始数据]
 * @param  {[type]} id_key        [主 key]
 * @param  {[type]} parrentId_key [父 key]
 * @return {[type]}               [格式化后的树形数据]
 */
const formatTreeData = (dataSource, id_key, parrentId_key) =>{
    // 深度复制一份,不想用 lodash 的,能够用其余办法
    // 深度复制是为了不想扭转原数组,如果不介意,能够间接用
    // const data = lodash.cloneDeep(dataSource);
    const data = JSON.parse(JSON.stringify(dataSource));

    data.forEach(i =>
        i.children = data.filter(j => j[parrentId_key] === i[id_key])
    );

    return data.filter(i =>
        !data.find(j => i[parrentId_key] === j[id_key])
    );
};

const res = formatTreeData(dataSource, "id", "pid");

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

正文完
 0