树状结构与数组转换
使用场景
后端传递嵌套数据
菜单权限等
树结构转数组
/**
* 树结构转数组
* @param {Object} arr 树结构
*/
export const treeToList = (arr) => {
let tree = JSON.parse(JSON.stringify(arr));
let queen = [];
let out = [];
queen = queen.concat(tree);
while (queen.length) {
let first = queen.shift();
if (first.children) {
queen = queen.concat(first.children);
delete first['children'];
}
out.push(first);
}
return out;
};
数组转树结构
/**
* 数组转树结构
* @param {Object} jsonData 数组
*/
export const listToTree = (jsonData) => {
const cloneData = JSON.parse(JSON.stringify(jsonData)); // 对源数据深度克隆
return cloneData.filter((father) => {
const branchArr = cloneData.filter(
(child) => father.id === child.parentId,
); // 返回每一项的子级数组
if (branchArr.length > 0) {
father.children = branchArr; // 如果存在子级,则给父级添加一个children属性,并赋值
}
return !father.parentId; // 返回第一层
});
};
本文来自博客园,作者:流云君,转载请注明原文链接:https://www.cnblogs.com/yun10011/p/16520480.html