用循環代替遞歸防止棧溢出性能
有些場景可能須要咱們把平級的數據轉換成樹結構,例如:code
let data = [ { id: 1, pid: 0 }, { id: 2, pid: 1 }, { id: 3, pid: 2 }, { id: 4, pid: 3 }, { id: 5, pid: 3 }, { id: 6, pid: 3 }, { id: 4, pid: 10 }, { id: 7, pid: 10 }, { id: 10, pid: 20 } ]
這樣的數據咱們通常想到的就是一個遞歸就搞定,可是遞歸嵌套太多會出現性能問題。全部能夠用循環來代替遞歸例如:對象
function computedTree(treeData, id, pid) { let arr = [] treeData.forEach((item, index) => { let isParent = false treeData.forEach(item2 => { if (item[pid] === item2[id]) { isParent = true !Array.isArray(item2.children) && (item2.children = []) item2.children.push(item) } }) !isParent && arr.push(index) }) return treeData.filter((item, index) => arr.indexOf(index) > -1) } let result = computedTree(data, 'id', 'pid') console.log(JSON.stringify(result)) //result [{"id": 1,"pid": 0, "children": [ {"id": 2,"pid": 1,"children": [ {"id": 3,"pid": 2,"children": [ {"id": 4,"pid": 3}, {"id": 5,"pid": 3}, {"id": 6,"pid": 3} ]} ]} ]}, {"id": 10,"pid": 20,"children": [{"id": 4,"pid": 10}, {"id": 7,"pid": 10}] }]
這裏的原理很簡單,就是利用對象的淺拷貝
,把全部子父關係作一個轉換就獲得結果。而後把沒有父級的作爲頂級返回就獲得想要的數據,若不想污染數據源可先cloneDeep
後再作計算,