三級聯(lián)動的省市區(qū)(將有父子關系的一維數(shù)組轉換成樹形結構(多維)數(shù)據(jù))

測試數(shù)據(jù)

areas = [ {id: 1, areaCode: 110000, areaName: '北京市', pid: null}, {id: 2, areaCode: 220000, areaName: '河北省', pid: null}, {id: 3, areaCode: 111100, areaName: '北京市', pid: 1}, {id: 4, areaCode: 111101, areaName: '昌平區(qū)', pid: 3}, {id: 5, areaCode: 111102, areaName: '海淀區(qū)', pid: 3}, {id: 6, areaCode: 220100, areaName: '張家口市', pid: 2}, {id: 7, areaCode: 220200, areaName: '保定市', pid: 2}, {id: 8, areaCode: 220101, areaName: '懷來縣', pid: 6}, {id: 9, areaCode: 220102, areaName: '赤城縣', pid: 6}, {id: 10, areaCode: 220201, areaName: '徐水縣', pid: 7}, {id: 11, areaCode: 220202, areaName: '唐縣', pid: 7}, ]

記錄遍歷次數(shù)

let i=0;

核心算法

function translateDataToTre2(data) {

? let parents = data.filter(value => value.pid === 'undefined' || value.pid === null || value.pid === '')

? let children = data.filter(value => value.pid !== 'undefined' && value.pid !== null && value.pid !== '')

? let translator = (parents, children) => {

? ? parents.forEach((parent) => {

? ? ? children.forEach((current, index) => {

? ? ? i++

? ? ? ? if (current.pid === parent.id) {

? ? ? ? ? let temp = JSON.parse(JSON.stringify(children))

? ? ? ? ? temp.splice(index, 1)

? ? ? ? ? translator([current], temp)

? ? ? ? ? typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current]

? ? ? ? }

? ? ? })

? ? })

? }

? translator(parents, children)

? return parents

}

console.log(i)

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容