js將list轉化為tree格式的幾種寫法
阿新 • • 發佈:2020-09-10
最近在考慮一個樹狀結構儲存。
最終需要將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)