JS遍歷樹層級關系實現原理解析
1.遍歷樹的層級關系
1)先整理數據
2)找到id和數據的映射關系
3)然后找到父節點的數據,進行存儲
代碼如下
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); },
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: