方法一:按层级遍历
function treeOptionsFromQueryResult1(data, id, pid, rootPid) {
//data:源数据,id:元素id,pid:父元素id;rootPid:根节点id
const parentChildrenMap = {}; //首先构造所有父子关系的对象,即每一层数据与下级数据对应关系
each(data, (row) => {
if (parentChildrenMap[row[pid]] === undefined) {
parentChildrenMap[row[pid] = [];
}
parentChildrenMap[row[pid].push({
id: row[id],
children: [],
name: row.name,
});
});
let q = [];
q.push(parentChildrenMap[rootPid][0]);//可以理解为children元素,首次push根节点
while (q.length > 0) { //判断如果p长度大于0执行逻辑,与下面每次shift删除首元素构成遍历
const curNode = q.shift();//取到当前节点就是q里面的首节点,并在q里面删除
curNode.children = parentChildrenMap[curNode.id];//根据之前父子对应关系给当前节点赋予children子元素集合
q = union(q, curNode.children); //union为lodash库里面的方法,遍历children元素,为每一项赋它的子元素集合
}
return parentChildrenMap[rootPid];//返回对象里面的根节点对应的值
}
方法二:
function getTreeData(data, id, pid, children, rootPid) {
const cloneData = JSON.parse(JSON.stringify(data));
return cloneData.filter((father) => {
const childrenArr = cloneData.filter(child => father[id] === child[pid]);
father[children] = childrenArr.length > 0 ? childrenArr : '';
return father[pid] === rootPid;
});
}
网友评论