递归的实际使用场景
数据源:
const tree = [
{
value: '一级 1',
text: '一级 1',
children: [
{
value: '二级 1-1',
text: '二级 1-1',
children: [
{
value: '三级 1-1-1',
text: '三级 1-1-1',
children: [
{ value: '四级 1-1-1-1', text: '四级 1-1-1-1' },
{ value: '四级 1-1-1-2', text: '四级 1-1-1-2' }
]
},
{ value: '三级 1-1-2', text: '三级 1-1-2' }
]
},
{
value: '二级 1-2',
text: '二级 1-2',
children: [
{ value: '三级 1-2-1', text: '三级 1-2-1' },
{ value: '三级 1-2-2', text: '三级 1-2-2' }
]
}
]
},
{
value: '一级 2',
text: '一级 2',
children: [
{
value: '二级 2-1',
text: '二级 2-1',
children: [
{ value: '三级 2-1-1', text: '三级 2-1-1' },
{ value: '三级 2-1-2', text: '三级 2-1-2' }
]
},
{ value: '二级 2-2', text: '二级 2-2' }
]
},
{
value: '一级 3',
text: '一级 3',
children: [
{ value: '二级 3-1', text: '二级 3-1' },
{ value: '二级 3-2', text: '二级 3-2' }
]
}
]
1、递归去除falg为false的项
const filterFalseByFlag = tree =>cloneDeep(tree).filter(item => { if (item.children?.length) item.children = filterFalseByFlag(item.children) return item.flag })
2、递归为每层数据添加level
const setLevel = (tree, level = 1) => cloneDeep(tree).map(item => { item.level = level if (item.children?.length) item.children = setLevel(item.children, level + 1) return item })
3、根据value值获取该节点所有的父级节点
const getParentsByValue = (tree, value) => { for (const item of tree) { if (item.children?.length) { const nodeList = getParentsByValue(item.children, value) if (nodeList) return nodeList.concat(item) } if (item.value === value) return [item] } }
const parents = getParents(tree, '四级 1-1-1-1')
4、根据value获取当前节点(依赖于getParentsByValue)
const getNodeByValue = (tree, value) => { const parents = getParentsByValue(tree, value) return parents.find(item => item.value === value) }
另一种方式(不依赖getParentsByValue,这个比较好):
const getNodeByValue = (tree, value) => { for (const item of tree) { if (item.value === value) { return item } else if (item.children?.length) { const node = getNodeByValue(item.children, value) if (node) return node } } }
5、获取当前节点的所有子节点(依赖于getParentsByValue和getNodeByValue)
const getChildsByNode = (list, childs = []) => { for (const item of list) { childs.push(item) if (item.children?.length) getChildsByNode(item.children, childs) } return childs }
const node = getNodeByValue(tree, '二级 1-2')
const childs = getChildsByNode([node])