JS遍歷樹層級關(guān)系實(shí)現(xiàn)原理解析
1.遍歷樹的層級關(guān)系
1)先整理數(shù)據(jù)
2)找到id和數(shù)據(jù)的映射關(guān)系
3)然后找到父節(jié)點(diǎn)的數(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. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向2. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明3. CSS hack用法案例詳解4. PHP設(shè)計(jì)模式中工廠模式深入詳解5. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)6. asp中response.write("中文")或者js中文亂碼問題7. ASP.NET MVC遍歷驗(yàn)證ModelState的錯(cuò)誤信息8. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測可用)9. ASP 處理JSON數(shù)據(jù)的實(shí)現(xiàn)代碼10. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法
