数组与树结构相互转换
原始数组 arr
const arr = [
{
id: 1, title: '中国', parentId: 0 },
{
id: 2, title: '浙江省', parentId: 1 },
{
id: 3, title: '杭州市', parentId: 2 },
{
id: 4, title: '西湖区', parentId: 3 },
{
id: 5, title: '河南省', parentId: 1 },
{
id: 6, title: '郑州市', parentId: 5 },
];
Array To Tree
/* Array To Tree */
function arrToTree(data) {
let result = [];
if (!Array.isArray(data)) {
return result;
}
let map = new Map();
data.forEach(item => {
delete item.children;
map[item.id] = item;
});
data.forEach(item => {
let parent = map[item.parentId];
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
result.push(item);
}
});
return result;
}
Tree To Array
/* Tree To Array */
function treeToList(data) {
let res = [];
const func = (tree) => {
tree.forEach((item) => {
if (item.children) {
func(item.children);
delete item.children;
}
res.push(item);
});
};
func(data);
return res;
}
查找 Tree 路径 (一级/二级)
/**
* 根据 id 查找所在目录路径
* @param { 树结构的数组数据 } tree
* @param { 要查找的 id } id
* @param { 初始路径 } path
* @returns
*/
function parseTreePath(tree, id, path = '') {
for (let i = 0; i < tree.length; i++) {
let tempPath = path;
// 避免出现在最前面的/
tempPath = `${
tempPath ? tempPath + '/' : tempPath}${
tree[i].title}`;
if (tree[i].id == id) {
return tempPath;
} else if (tree[i].children) {
let reuslt = parseTreePath(tree[i].children, id, tempPath);
if (reuslt) {
return reuslt;
}
}
}
}
parseTreePath(tree, 5)
parseTreePath(tree, 4)