最近在考慮一個樹狀結構存儲。
最終需要將list轉化為tree格式
源數據示例
源數據共401條
[{ "menuId" : "5f50c5fb8f0d74536bbfb7a4", "menuName" : "菜單管理", "parentMenuId" : null },
{ "menuId" : "5f524416ff216c2cbc554907", "menuName" : "頻道管理", "parentMenuId" : "5f50c5fb8f0d74536bbfb7a4" },
{ "menuId" : "5f576677d9588f3d78fbdb74", "menuName" : "分類管理", "parentMenuId" : "5f524416ff216c2cbc554907" },
{ "menuId" : "5f588b22499cd2538411b98a", "menuName" : "發布管理", "parentMenuId" : "5f50c5fb8f0d74536bbfb7a4" },
{ "menuId" : "5f588b85499cd2538411b98b", "menuName" : "權限管理", "parentMenuId" : "5f50c5fb8f0d74536bbfb7a4" },
{ "menuId" : "5f588f8358bc0d3e647403a1", "menuName" : "菜單管理", "parentMenuId" : "5f588b85499cd2538411b98b" }
...]
方法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
})}