测试数据
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: '昌平区', pid: 3}, {id: 5, areaCode: 111102, areaName: '海淀区', 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}, ]
记录遍历次数
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)