
省市区树结构扁平化转换结构
本文旨在解决如何将嵌套的省市区结构树扁平化为指定格式的结构,以满足特定需求。
需求:
数据结构:
树形结构的数据示例如下:
[
{
"code": "110000",
"value": "北京市",
"checked": "1",
"children": [
{
"code": "110100",
"value": "北京市",
"checked": "1",
"children": [
{
"code": "110101",
"value": "东城区",
"checked": "1"
},
{
"code": "110102",
"value": "西城区",
"checked": "1"
}
]
}
]
},
{
"code": "120000",
"value": "天津市",
"checked": "1",
"children": [
{
"code": "120100",
"value": "天津市",
"checked": "1",
"children": [
{
"code": "120101",
"value": "和平区",
"checked": "0"
},
{
"code": "120102",
"value": "河东区",
"checked": "1"
}
]
}
]
}
]扁平化处理:
以下是扁平化处理的 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)扁平化结果:
[
{
provinceAreald : '110000',
cityAreald: null, //如2级全部选中为null
countryAreald: null, //如3级全部选中为null
actualAreaLevel:'1'
},
{
provinceAreald : '120000',
cityAreald: '120100', //如2级全部选中为null
countryAreald: '120102', //如3级全部选中为null
actualAreaLevel:'3' //层级
}
]以上就是如何将嵌套的省市区树结构扁平化为指定格式,以满足不同选择的地址获取需求?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号