JS遍歷樹層級關(guān)系實現(xiàn)原理解析
1.遍歷樹的層級關(guān)系
1)先整理數(shù)據(jù)
2)找到id和數(shù)據(jù)的映射關(guān)系
3)然后找到父節(jié)點的數(shù)據(jù),進行存儲
代碼如下
test() { const list = [ { id: '123', parentId: '', children: [] }, { id: '124', parentId: '123', children: [] }, { id: '125', parentId: '124', children: [] }, { id: '126', parentId: '125', children: [] }, { id: '127', parentId: '126', children: [] } ]; const mapList = []; const tree = []; list.forEach(item => {mapList[item.id] = item; }); list.forEach(item => { const parentNode = mapList[item.parentId]; if (!parentNode) { if (!item.children) { item.children = [] } tree.push(item); } else {if (!parentNode.children) {parentNode.children = []} parentNode.children.push(item); } }); console.log('tree', tree); },
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向2. CSS可以做的幾個令你嘆為觀止的實例分享3. JSP+Servlet實現(xiàn)文件上傳到服務(wù)器功能4. 淺談由position屬性引申的css進階討論5. php使用正則驗證密碼字段的復(fù)雜強度原理詳細講解 原創(chuàng)6. asp批量添加修改刪除操作示例代碼7. 基于javaweb+jsp實現(xiàn)企業(yè)財務(wù)記賬管理系統(tǒng)8. vue項目登錄成功拿到令牌跳轉(zhuǎn)失敗401無登錄信息的解決9. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗分享10. vue前端RSA加密java后端解密的方法實現(xiàn)

網(wǎng)公網(wǎng)安備