1.过滤树结构数据,按某个子项的属性过滤树结构数据,不改变数据结构,返回需要的树。
let filterTree=function (nodes, predicate) {
// 如果已经没有节点了,结束递归
if (!(nodes && nodes.length)) {
return;
}
const newChildren = [];
for (const node of nodes) {
const subs = filterTree(node.children, predicate);
// 以下两个条件任何一个成立,当前节点都应该加入到新子节点集中
// 1. 子孙节点中存在符合条件的,即 subs 数组中有值
// 2. 自己本身符合条件
if ((subs && subs.length) || predicate(node)) {
node.children = subs;
newChildren.push(node);
}
}
return newChildren.length ? newChildren : void 0;
}
2.返回满足条件的项的一维数组,不含children属性
let getItems=function(tree, condition){
let newChildren=[]
for(let item of tree){
if(condition(item)){
if(item.children){
let {children,...rest}=item
newChildren.push(rest)
}else{
newChildren.push(item)
}
}
if(item.children&&item.children.length>0){
let subs=getItems(item.children,condition)
newChildren.push(...subs)
}
}
return newChildren
}
let menu=getItems(navTabList,item=>item.env.includes('pro'))
3.返回选中项的某个属性组成的数组,多应用于树返回选中的项的id
getTreePropArr(tree, prop,cdt) {
let props = []
let forTree = function (tree, prop) {
tree.forEach(item => {
if(cdt(item)){
props.push(item[prop])
}
if (item.children && item.children.length > 0) {
forTree(item.children, prop)
}
})
}
forTree(tree,prop)
return props
}
let Ids=this.getTreePropArr(this.treeData,'id',item=>item.checked)
4.树结构不变,转换key值
toTreeFormat(tree) {
let forTree = function (tree) {
tree.forEach((item, index) => {
tree[index] = {
id: item.perMd,
title: item.Name,
expend: true,
checked: item.isCheck,
children: item.subP
}
if (item.subP && item.subP.length > 0) {
tree[index].children = item.subP
forTree(item.subP)
}
})
return tree
}
return forTree(tree)
},
参考:
https://segmentfault.com/q/1010000018197249/a-1020000018203261