JS遍歷樹層級(jí)關(guān)系實(shí)現(xiàn)原理解析
1.遍歷樹的層級(jí)關(guān)系
1)先整理數(shù)據(jù)
2)找到id和數(shù)據(jù)的映射關(guān)系
3)然后找到父節(jié)點(diǎn)的數(shù)據(jù),進(jìn)行存儲(chǔ)
代碼如下
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); },
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. IDEA 2020.1.2 安裝教程附破解教程詳解2. Spring如何集成ibatis項(xiàng)目并實(shí)現(xiàn)dao層基類封裝3. Java PreparedStatement用法詳解4. idea設(shè)置提示不區(qū)分大小寫的方法5. 40個(gè)Java集合面試問題和答案6. Java利用TCP協(xié)議實(shí)現(xiàn)客戶端與服務(wù)器通信(附通信源碼)7. django queryset相加和篩選教程8. IntelliJ IDEA導(dǎo)出項(xiàng)目的方法9. asp.net core項(xiàng)目授權(quán)流程詳解10. ASP.NET MVC使用異步Action的方法

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