
如何将省市区树形结构转换成扁平化结构?
我们有一个树形数据结构,表示省市区之间的关系,其中:
现在,我们需要将这个树形结构转换成扁平化结构。扁平化结构是一个数组,其中每个元素都是一个对象,包含以下字段:
转换规则如下:
下面是一个将树形结构转换成扁平化结构的 JavaScript 函数:
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号