
省市区树结构扁平化转换
给了省市区的树状结构,只有选中节点的check为1,其他都为null。我们需要做的就是扁平化数据结构,把所有被选中的省、市、区代码放到一个数组中。
解决方案
思路是递归遍历树结构,将选中状态向下传递。具体步骤如下:
遍历list,对于每个节点:
代码示例
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": "西城区",
"checked": null
}
]
}
]
},
/* 省略其他省市区 */
];
const result = getCheckedList(tree);
console.log(result);结果:
[ [ "110000", "110100", "110101" ], [ "110000", "110100", "110102" ], /* 省略其他选中项 */ ]
以上就是如何将省市区树结构扁平化为选中节点的代码数组?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号