【JavaScript】 获取树被选中的顶级节点(小记)
1. 若存在一棵树
例如:
const tree = [
{
id: '1',
children: [
{
id: '1-1',
children: [
{
id: '1-1-1',
children: [
{
id: '1-1-1-1',
children: []
},
{
id: '1-1-1-2',
children: []
},
{
id: '1-1-1-3',
children: []
}
]
}
]
},
{
id: '1-2',
children: [
{
id: '1-2-1',
children: []
}
]
}
]
},
{
id: '2',
children: [
{
id: '2-1',
children: [
{
id: '2-1-1',
children: []
}
]
},
{
id: '2-2',
children: [
{
id: '2-2-1',
children: []
}
]
}
]
}
]
2. 期望结果
lookAtCheckedTopNodes(['1', '2'], tree) // => ['1', '2']
lookAtCheckedTopNodes(['1-1-1-1', '1-1-1-2', '1-1-1-3'], tree) // => ['1-1']
lookAtCheckedTopNodes(['1-1-1-1', '1-1-1-2', '1-1-1-3', '1-2'], tree) // => ['1']
lookAtCheckedTopNodes(['1-1-1-1', '1-1-1-2', '1-1-1-3', '1-2-1'], tree) // => ['1']
lookAtCheckedTopNodes(['1-1', '1-2'], tree) // => ['1']
3. 实现
function getCheckNodeAndParent(checked = [], tree = []) {
const loop = (tree, parent = null, map = {}) => {
for (const item of tree) {
item.parent = parent
if (checked.includes(item.id)) {
map[item.id] = item
continue
}
if (item.children && item.children.length) {
const newMap = loop(item.children, item, map)
map = { ...map, ...newMap }
}
}
return map
}
return loop(tree)
}
function loopLookParent(map) {
// 递归重新遍历map,找到所有的父节点
const newMap = {}
let flag = false
for (const key in map) {
const item = map[key]
const { parent } = item
if (!parent) {
newMap[key] = item
continue
}
const { id, children } = parent
const parentChildrenCheckedAll = children?.every((child) => map[child.id])
if (parentChildrenCheckedAll) {
flag = true
newMap[id] = parent
} else {
newMap[key] = item
}
}
if (flag) {
return loopLookParent(newMap)
}
return newMap
}
export function lookAtCheckedTopNodes(checked = [], tree = []) {
const map = getCheckNodeAndParent(checked, tree)
return loopLookParent(map)
}
为之则易,不为则难。
本文作者:Code_You
本文链接:https://www.cnblogs.com/coderDemo/p/18211051
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2023-05-24 Vue3 useReusableTemplate 优雅的复用模板代码