省市区树结构扁平化转换结构?
数据:check:1 为选中
[
{
"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"
}]
}]
}
]
转化为:如果3级都选中了那就只获取1级和2级,如果2级都选中了,只获取1级,如3级选中某几个,获取1,2,3级
[
{
provinceAreald : '110000',
cityAreald: null //如2级全部选中为null
countryAreald: null //如3级全部选中为null
actualAreaLevel:'1'
},
{
provinceAreald : '120000',
cityAreald: '120100' //如2级全部选中为null
countryAreald: '120102' //如3级全部选中为null
actualAreaLevel:'3' //层级
}
]
求搭救
回复
1个回答
test
2024-07-08
function getNewData(data) {
let d = []
for (let province of data) {
if (province.checked == 1) {
let obj = {
provinceAreald: province.code,
cityAreald: null,
countryAreald: 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)
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容