有时候我们遇到后台返回不是标准结构,但是我们组件又是树结构类型的数据怎么办呢? 这时候就需要转换一下结构了
buildTree(data,id,faid) { //对树请求返回数据进行处理为el-tree数据结构
// 使用Map来存储节点,以便快速查找
const map = new Map();
// 遍历数据,将每个节点添加到map中,并初始化children数组
data.map(item => {
map.set(item[id], { ...item, children: [] });
});
// 使用reduce来构建树
// 注意:这里实际上没有使用reduce的累加器特性,只是用它来遍历数组
data.reduce((_, item) => {
// 查找父节点
const parentid = item[faid];
const parent = parentid ? map.get(parentid) : null;
// 将当前节点添加到父节点的children数组中(如果存在父节点)
if (parent) {
parent.children.push(map.get(item[id]));
}
return null;
}, null);
// 找到根节点(parentid为null的节点)
const roots = [];
map.forEach(node => {
if (!node[faid]) {
roots.push(node);
}
});
return roots;
},
使用buildTree(对象数组,id,上一级父节点id)就可以得到el-tree数据结构
即得到data:[{id:xxx,faid:xxx,children:[...]},....],id和faid为举例,具体以实际数据为准!
但是如果我们修改或增加节点后要返回的参数又必须是对象数组,且不能像上述一样嵌套,怎么办呢?
那么就需要数组扁平化咯!
flattenTree(tree) {
let result = [];
function flatten(nodes) {
nodes.forEach(node => {
let copy = { ...node }; // 创建节点对象的浅拷贝
delete copy.children; // 删除拷贝对象的 children 属性
result.push(copy); // 将拷贝对象添加到结果数组中
if (node.children && node.children.length > 0) {
flatten(node.children); // 递归处理子节点
}
});
}
flatten(tree); // 调用递归函数开始扁平化过程
return result; // 返回扁平化的结果数组
},
使用flattenTree(树结构数据)就可以得到树结构转换为对象数组的数据了,前提是子节点是在父节点的children属性中。
感谢阅读