
省市区树结构扁平化转换结构
给定一棵表示省市区的树结构数据,需要将其扁平化转换,以满足如下要求:
解决方案
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)以上就是如何将省市区树结构数据扁平化转换,以便满足特定条件下的筛选要求?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号