在看一个掘金的帖子 https://juejin.cn/post/6983904373508145189 “扁平数据结构转 Tree”。
看的时候在想,自己很少用 Map 对象,要不试试用 Map 改造一下,结果改造失败,找了半天原因,靠同事指了出来。
let arr = [
    { id: 1, name: "部门 1", pid: 0 },
    { id: 2, name: "部门 2", pid: 1 },
    { id: 3, name: "部门 3", pid: 1 },
    { id: 4, name: "部门 4", pid: 3 },
    { id: 5, name: "部门 5", pid: 4 },
];
let result = [];
function arrayToTree1(items) {
    const result = [];
    const itemMap = {};
    for (const item of items) {
        itemMap[item.id] = { ...item, children: [] };
    }
    for (const item of items) {
        const id = item.id;
        const pid = item.pid;
        const treeItem = itemMap[id];
        if (pid === 0) {
            result.push(treeItem);
        } else {
            if (!itemMap[pid]) {
                itemMap[pid] = {
                    children: [],
                };
            }
            itemMap[pid].children.push(treeItem);
        }
    }
    return result;
}
result = arrayToTree1(arr);
console.log(result);
console.log("========");
function arrayToTree2(items) {
    const result = [];
    const itemMap = new Map();
    items.map((item, index) => {
        itemMap.set(item.id, { ...item, children: [] });
    });
    items.map((item, index) => {
        const id = item.id;
        const pid = item.pid;
        const treeItem = itemMap.get(id);
        if (pid === 0) {
            result.push(treeItem);
        } else {
            if (!itemMap.get(pid)) {
                itemMap.set(pid, { children: [] });
            }
            itemMap.set(pid, {
                ...itemMap.get(pid),
                children: itemMap.get(pid).children.concat(treeItem),
            });
        }
    });
    return result;
}
result = arrayToTree2(arr);
console.log(result);
https://i.v2ex.co/1G1gNIox.png
中途甚至试着问了问 chat ,它没看出来啥区别敷衍了一下我 TAT 。后面我再想想能不能抢救一下 arrayToTree2
===接上一贴:裸辞了,但是单子还没提,总之大小领导都通知了。这里的规矩是通知完点头后才能提单子,这会儿学点自己想学的,边休息变沉淀一下了。
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.