成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

JS遍歷樹層級關(guān)系實現(xiàn)原理解析

瀏覽:78日期:2024-04-22 15:36:20

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)。

標(biāo)簽: JavaScript
相關(guān)文章: