js 手写数组转tree

  1. 先找到根(父)节点,然后根据根节点的id和数组元素的pid找到对应父子关系
  2. 重复上一步骤
    const getTree = (root, list) => {
        if(!Array.isArray(list)) throw 'list must be Array' 
        root = root || list.find(v => !v.pid)
        if (root == undefined) return root
        const children = list.filter(v => root.id === v.pid)
        if (children.length) {
            root.children = [].concat(children)
            children.forEach(node => getTree(node, list))
        }
        return root
    }
posted @ 2022-06-19 16:41  IslandZzzz  阅读(117)  评论(0编辑  收藏  举报