
扁平化省市区树结构中的选中项
在省市区树形结构中,需要对选中项进行扁平化转换。树形结构类似如下所示:
{ "code": "110000", "value": "北京市", "check": 1, // 选中标识 "children": [ { "code": "110100", "value": "北京市", "check": null, // 未选中标识 "children": [ { "code": "110101", "value": "东城区", "check": null // 未选中标识 }, { "code": "110102", "value": "西城区", "check": null // 未选中标识 } ] } ]}
扁平化后的结果需要满足如下要求:
如果一级选中,则记录一级、二级和三级code如果二级选中,则记录二级和三级code如果三级选中,则仅记录三级code
最终扁平化结果如下:
[ [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' ] ]
以上就是如何将扁平化省市区树结构中的选中项进行扁平化转换?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1557844.html
微信扫一扫
支付宝扫一扫