zoukankan      html  css  js  c++  java
  • js将list转化为tree格式的几种写法

    最近在考虑一个树状结构存储。

    最终需要将list转化为tree格式

    源数据示例

    源数据共401条

    方法1

    递归遍历children

    共执行 递归 161202 次 5ms左右时间(win10/i7 8th/16G)

    const list = [...]
    // 递归 161202 次 5ms左右时间
    const list2tree1 = (list, parentMenuId) => {
        return list.filter(item => {
            if (item.parentMenuId === parentMenuId) {
                item.children = list2tree1(list, item.menuId)
                return true
            }
            return false
        })
    }
    list2tree1(list, null)

    方法2

    因为方法1是查询的children,所以每次必须全部遍历。

    我们换个思路,查询每个节点的parent,查到paret之后,内部循环就可以截止了。(使用find方法)

    共执行 68976 次 3.6ms左右

    const list = [...]
    // 68976 次 3.6ms左右
    const list2tree2 = (list, parentMenuId) => {
        return list.filter(item => {
            if (item.parentMenuId !== parentMenuId) {
                let parent = list.find(parent => parent.menuId === item.parentMenuId)
                if (!parent.children) parent.children = []
                parent.children.push(item)
                return false
            }
            return true
        })
    }
    list2tree2(list, null)

    方法3

    在方法2的基础上,将每次find的parentNode缓存起来,减少相同parent的查询次数

    共执行 15337 次 1.8ms左右

    const list = [...]
    // 15337 次 1.8ms左右 cache parent
    const list2tree3 = (list, parentMenuId) => {
        let parentObj = {}
        return list.filter(item => {
            if (item.parentMenuId !== parentMenuId) {
                if (!parentObj[item.parentMenuId]) {
                    parentObj[item.parentMenuId] = list.find(parent => parent.menuId === item.parentMenuId)
                    parentObj[item.parentMenuId].children = []
                }
                parentObj[item.parentMenuId].children.push(item)
                return false
            }
            return true
        })
    }
    list2tree3(list, null)

    方法4

    遍历tree之前,先遍历一遍数组,将数据缓存到object中。

    二次遍历,直接使用object中的缓存

    共执行 802 次 0.2ms左右

    const list = [...]
    // 802 次 0.2ms左右
    const list2tree4 = (list, parentMenuId) => {
        let menuObj = {}
        list.forEach(item => {
            item.children = []
            menuObj[item.menuId] = item
        })
        return list.filter(item => {
            if (item.parentMenuId !== parentMenuId) {
                menuObj[item.parentMenuId].children.push(item)
                return false
            }
            return true
        })
    }
    list2tree4(list, null)
     
     
  • 相关阅读:
    心血来潮学python
    lua中的table、stack和registery
    wrapper for lua
    FT232RL变砖之后
    12.04 redmine
    Webpack 概念
    如何学习 Webpack
    React基础篇
    Intellij实用技巧
    一行代码搞定图片缩放、旋转、加水印
  • 原文地址:https://www.cnblogs.com/shb190802/p/13647203.html
Copyright © 2011-2022 走看看