遇到需求:
只展示有三层的数据,需要过滤掉不满足三层的。
实现代码:
使用的若伊框架,在封装好的 handleTree
方法里,加了个 level
的参数
/**
* 构造树型结构数据
* @param {*} data 数据源
* @param {*} id id字段 默认 'id'
* @param {*} parentId 父节点字段 默认 'parentId'
* @param {*} children 孩子节点字段 默认 'children'
* @param {*} level 只展示满足层级节点
*/
export function handleTree(data, id, parentId, children, level) {
let config = {
id: id || 'id',
parentId: parentId || 'parentId',
childrenList: children || 'children'
};
var childrenListMap = {};
var nodeIds = {};
var tree = [];
// 构建初步的childrenListMap
for (let d of data) {
let parentId = d[config.parentId];
if (childrenListMap[parentId] == null) {
childrenListMap[parentId] = [];
}
nodeIds[d[config.id]] = d;
childrenListMap[parentId].push(d);
}
// 找到根节点
for (let d of data) {
let parentId = d[config.parentId];
if (nodeIds[parentId] == null) {
tree.push(d);
}
}
// 递归适应childrenList,同时计算层级
for (let t of tree) {
adaptToChildrenList(t);
}
function adaptToChildrenList(o) {
if (childrenListMap[o[config.id]] !== null) {
o[config.childrenList] = childrenListMap[o[config.id]];
}
if (o[config.childrenList]) {
for (let c of o[config.childrenList]) {
adaptToChildrenList(c);
}
}
}
// 如果传入level,则表示只返回达到level层级的tree
function hasMinimumDepth(node, depth, level) {
if (level) {
if (!node[config.childrenList] || !node[config.childrenList].length) {
return false;
} else {
depth++
if (depth === level) {
return true;
} else {
return node[config.childrenList].every(child => hasMinimumDepth(child, depth, level));
}
}
} else { // 考虑到有其他地方使用该方法,所以不改动原先树形结构数据,直接返回true
return true;
}
}
return tree.filter(node => hasMinimumDepth(node, 1, level));
}