
扁平化省市区树结构中的选中项
在省市区树形结构中,需要对选中项进行扁平化转换。树形结构类似如下所示:
{
"code": "110000",
"value": "北京市",
"check": 1, // 选中标识
"children": [
{
"code": "110100",
"value": "北京市",
"check": null, // 未选中标识
"children": [
{
"code": "110101",
"value": "东城区",
"check": null // 未选中标识
},
{
"code": "110102",
"value": "西城区",
"check": null // 未选中标识
}
]
}
]
}扁平化后的结果需要满足如下要求:
最终扁平化结果如下:
[ [110000, 110100, 110101], [110000, 110100, 110102] ]
实现扁平化的思路是进行递归遍历,将选中标识传递下去。代码如下:
/**
* 获取所有被选中的code
* @param {any[]} list 树形结构
* @param {string[]} parentList 到父级所有的code的数组
* @param {boolean} parentChecked 上级是否被选中,若上级被选中,则下面所有的子选项均是被选中的数据
*/
const getCheckedList = (list, parentList = [], parentChecked = false) => {
let result = [];
if (!Array.isArray(list)) {
return result;
}
list.forEach((item) => {
const checked = parentChecked || item.check; // 父级被选中或当前被选中,均认为是被选中
const codeList = parentList.concat(item.code);
if (item.children) {
// 当前不是最内层
result = result.concat(getCheckedList(item.children, codeList, checked));
} else {
// 已到最内层
if (checked) {
result.push(codeList);
}
}
});
return result;
};使用示例:
const tree = [
{
"code": "110000",
"value": "北京市",
"check": 1,
"children": [
{
"code": "110100",
"value": "北京市",
"check": null,
"children": [
{
"code": "110101",
"value": "东城区",
"check": null
},
{
"code": "110102",
"value": "西城区",
"check": null
}
]
}
]
},
{
"code": "130000",
"value": "河北省",
"check": null,
"children": [
{
"code": "130100",
"value": "石家庄市",
"check": "1",
"children": [
{
"code": "130102",
"value": "长安区",
"check": null
},
{
"code": "130104",
"value": "桥西区",
"check": null
}
]
},
{
"code": "130200",
"value": "唐山市",
"check": null,
"children": [
{
"code": "130202",
"value": "路南区",
"check": null,
},
{
"code": "130203",
"value": "路北区",
"check": null,
}
]
}
]
},
{
"code": "150000",
"value": "内蒙古自治区",
"check": null,
"children": [
{
"code": "150100",
"value": "呼和浩特市",
"check": null,
"children": [
{
"code": "150102",
"value": "新城区",
"check": null
},
{
"code": "150103",
"value": "回民区",
"check": 1
}
]
}
]
}
];
console.log(getCheckedList(tree)); // [ [ '110000', '110100', '110101' ], [ '110000', '110100', '110102' ], [ '130000', '130100', '130102' ], [ '130000', '130100', '130104' ], [ '150000', '150100', '150103' ] ]以上就是如何将扁平化省市区树结构中的选中项进行扁平化转换?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号