首页 信息互联🚀,终生学习

记录一下:

假设原始数据如下

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




文章评论

    若志奕鑫 访客ChromeWindows
    2021-09-18 21:23   回复

    你就是这个

    Teacher Du 访客ChromeWindows
    2021-09-6 19:10   回复

    过来学习一下!