省市区树结构扁平化转换结构
给定一棵表示省市区的树结构数据,需要将其扁平化转换,以满足如下要求:
解决方案
function getNewData(data) { let d = [] for (let province of data) { if (province.checked == 1) { let obj = { provinceAreald: province.code, cityAreald: null, // 如2级全部选中为null countryAreald: null, // 如3级全部选中为null actualAreaLevel: '1', } const cityArr = cityCheck(province, obj, d) if (cityArr.length == province.children.length) { Object.assign(obj, { cityAreald: null, actualAreaLevel: '1', }) d.push(obj) // 2级菜单被<全部>选中 } else { d.push(...cityArr) // 2级菜单被<部分>选中 } } } function cityCheck(province, obj, d) { let cityArr = [] for (let city of province.children) { if (city.checked == 1) { Object.assign(obj, { cityAreald: city.code, actualAreaLevel: '2', }) // 参数obj, d可能被改变 const countryArr = countryCheck(city, obj, d) if (countryArr.length == city.children.length) { Object.assign(obj, { countryAreald: null, actualAreaLevel: '2', }) cityArr.push(obj) // 3级菜单被<全部>选中 } else { d = d.push(...countryArr) // 3级菜单被<部分>选中 } } } return cityArr } function countryCheck(city, obj, d) { let countryArr = [] for (let country of city.children) { if (country.checked == 1) { countryArr.push( Object.assign(obj, { countryAreald: country.code, actualAreaLevel: '3', }) ) } } return countryArr } return d } const newData = getNewData(data) console.log(newData)