原生JS实现树状结构列表的转化

记录一下:

假设原始数据如下

let data = [
    {
        "id": "1",
        "name": "1",
        "fatherId": "0",
    },
    {
        "id": "2",
        "name": "1-1",
        "fatherId": "1"
    },
    {
        "id": "3",
        "name": "1-2",
        "fatherId": "1"
    },
    {
        "id": "4",
        "name": "1-1-1",
        "fatherId": "2"
    },
    {
        "id": "5",
        "name": "1-1-2",
        "fatherId": "2"
    },
    {
        "id": "6",
        "name": "2",
        "fatherId": "0"
    },
    {
        "id": "7",
        "name": "1-2-1",
        "fatherId": "3"
    }
];

使用map处理数据

const map = {};
const val = [];
data.forEach((item) => {
    map[item.id] = item;
});
data.forEach((item) => {
    const parent = map[item.fatherId];
    if (parent) {
        (parent.children || (parent.children = [])).push(item);
    } else {
        val.push(item);
    }
});

参考文档:https://www.cnblogs.com/zuoWendong/p/13265549.html

打赏
评论区
头像
    头像

    你就是这个

    头像
    Teacher Du
      

    过来学习一下!