JS遍歷樹層級關(guān)系實現(xiàn)原理解析
1.遍歷樹的層級關(guān)系
1)先整理數(shù)據(jù)
2)找到id和數(shù)據(jù)的映射關(guān)系
3)然后找到父節(jié)點的數(shù)據(jù),進(jìn)行存儲
代碼如下
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. docker容器調(diào)用yum報錯的解決辦法2. jsp中sitemesh修改tagRule技術(shù)分享3. Docker究竟是什么 為什么這么流行 它的優(yōu)點和缺陷有哪些?4. Django中如何使用Channels功能5. IntelliJ IDEA導(dǎo)出項目的方法6. 使用 kind 和 Docker 啟動本地的 Kubernetes環(huán)境7. python的json包位置及用法總結(jié)8. Python通過zookeeper實現(xiàn)分布式服務(wù)代碼解析9. php過濾器使用詳解10. 關(guān)于html嵌入xml數(shù)據(jù)島如何穿過樹形結(jié)構(gòu)關(guān)系的問題

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