js 手写数组转tree
- 先找到根(父)节点,然后根据根节点的id和数组元素的pid找到对应父子关系
- 重复上一步骤
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
}