递归方法和循环方法,我都写了两种代码,仅供参考。
三种递归方法,两种循环方法,本质上都一样,就是写法不一样,加油!!!
const arr = [{ id: 1, name: '广东', pid: 0},{ id: 11, name: '深圳', pid: 1},{ id: 12, name: '东莞', pid: 1},{ id: 112, name: '宝安区', pid: 11},{ id: 2, name: '湖南', pid: 0},{ id: 21, name: '长沙', pid: 2},{ id: 22, name: '岳阳', pid: 2}]
结果如下所示:
方法一:利用递归,类似于数据结构中的树形结构
核心思想:从根节点开始找子节点,一条路径找完,再返回上一级,遍历完所有数组即结束。
学习建议:递归本身我觉得有点难以理解,所以我建议学习递归的时候,在代码中打个断点,观察每一步是怎么走的,每一步的数据是什么。
const arrayToTree = (arr, pid) => {let result = []handleArr(arr, result, pid)return result}const handleArr = (arr, result, pid) => {arr.forEach(item => {if(item.pid === pid) {const newObj = {...item, children: []}result.push(newObj)handleArr(arr, newObj.children, item.id)}})}console.log(arrayToTree(arr, 0))
const arrayToTree = (arr, pid) => {const result = []arr.forEach(item => {if (item.pid === pid) { result.push(item)item.children = arrayToTree(arr, item.id)}})return result}console.log(arrayToTree(arr, 0))
function array2Tree(arr, pid) {return arr.filter(v => {if (v.pid === pid) {const children = array2Tree(arr, v.id)v.children = childrenreturn true}})}
方法二:利用循环,这个循环是有几层循环才能找到几级。
const result = []arr.forEach( item1 => {if (item1.pid === 0) {result.push(item1)const children1 = []arr.forEach( item2 => {if (item2.pid === item1.id) {children1.push(item2)item1.children = children1const children2 = []arr.forEach(item3 => {if(item3.pid === item2.id) {children2.push(item3)item2.children = children2}})}}) }})console.log(result)
const result = arr.filter(v => {if (v.pid === '') {const children = arr.filter(v2 => {return v2.pid === v.id})v.children = childrenreturn true}})console.log(result)
如果有错误,欢迎指正。