
省市区树结构扁平化转换结构
对于给定的省市区树结构数据,需要对其进行扁平化转换,并根据各层级的选中情况,只保留实际被选中的层级信息。
具体转换规则:
- 如果省、市、区三级都选中,则只保留省和市信息。
- 如果省、市都选中,则只保留省信息。
- 如果仅省选中,则保留省信息。
- 如果市、区都选中,则保留省、市、区信息。
- 如果单独选中市或区,则保留省、市、区信息。
实现方法:
可以使用递归遍历的方式,对省市区树进行逐层检查。具体实现如下:
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)
登录后复制
以上就是如何将省市区树结构扁平化转换,并根据选中情况只保留实际选中的层级信息?的详细内容,更多请关注米云其它相关文章!
