// 处理成tree
getTree(dataList) {
const tree = [];
const idMap = new Map();
dataList.forEach(item => {
item.isLeaf = true;
idMap.set(item.id, item);
});
dataList.forEach(item => {
if (idMap.has(item.pid)) {
item.isLeaf = false;
const parent = idMap.get(item.pid);
if (!parent.children) {
parent.children = [];
}
parent.children.push(item);
} else {
tree.push(item);
}
});
console.log(tree)
return tree;
}
idMap 对象用于存储每个节点的引用,以便在后面能够快速查找父节点,就是利用了 get(key) 方法来获取与节点 id 相对应的节点引用。
返回的tree是对象,可以用json.parse(json.stringify())
转换一下
- 二,去重
getTree(dataList) {
if(!dataList)return []
const tree = [];
const idMap = new Map();
dataList.forEach(item => {
idMap.set(item.id, item);
});
dataList.forEach(item => {
if (idMap.has(item.pid)) {
const parent = idMap.get(item.pid);
if (!parent.children) {
parent.children = [];
}
let idx = parent.children.findIndex(i=>i.id==item.id)
if(idx== -1){
parent.children.push(item);
}else{
parent.children.splice(idx,1,item)
}
} else {
tree.push(item);
}
});
return JSON.parse(JSON.stringify(tree));
},