数组转树形:
这里基于el-tree所需要的数据类型进行示例:
传入原数组 list 和数组内各个参数名 obj:
{
id: 'id', //key
pid: 'pId', //父节点id
children: 'children' //子节点数组
}
/**
* @description: 数组转成树新
* @param {Array} list
* @param {Object} obj
* @return {Array} treeList
*/
export const getTreeList = (list, obj) =>{
var id = obj.id || 'id';
var pid = obj.pid || 'pid';
var children = obj.children || 'children';
var idMap = {};
var treeList = [];
list.forEach(function (v) {
idMap[v[id]] = v;
});
list.forEach(function (v) {
var parent = idMap[v[pid]];
if (parent) {
!parent[children] && (parent[children] = []);
parent[children].push(v);
} else {
treeList.push(v);
}
});
return treeList;
}
树形数据的筛选:
传入源树以及一个筛选函数比如:
let funcFliter = (e) => { return e.name.indexOf('666') >= 0 }
/**
* @description: 筛选树结构数据
* @param {Array} tree
* @param {Function} func
* @return {Array}
*/
export const treeFilter = (tree, func) => {
// 使用map复制一下节点,避免修改到原树
return tree.map(node => ({ ...node })).filter(node => {
node.children = node.children && treeFilter(node.children, func)
return func(node) || (node.children && node.children.length)
})
}