js数组与树形结构互转

前端面试题

将数组转成树形结构,有如下数据结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 京东前端笔试题,实现数组与树的互相转换
const arr = [
{
id: 1,
pid: null,
name: "研发部",
},
{
id: 2,
pid: null,
name: "管理部",
},
{
id: 3,
pid: 1,
name: "前端研发部",
},
{
id: 4,
pid: 1,
name: "后端研发部",
},
{
id: 5,
pid: 2,
name: "行政管理部",
},
{
id: 6,
pid: 2,
name: "人力资源部",
},
{
id: 7,
pid: null,
name: "财务部",
},
{
id: 8,
pid: 4,
name: "Java后端研发部",
},
];

数组转树形结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 数组转树形结构.
const array2Tree = (array, pid = null) => {
return array.reduce((prev, cur) => {
if (cur.pid === pid) {
// 一级部门之间push加入.
const children = array2Tree(array, cur.id);
if (children.length) {
cur.children = children;
}
prev.push(cur);
}
return prev;
}, []);
};

const tree = array2Tree(arr);
console.log("result tree", tree);

树形结构转数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 树转数组 结构
const tree2Array = (tree) => {
return tree.reduce((prev, cur) => {
if (!cur.children) {
prev.push(cur);
} else {
const subList = tree2Array(cur.children); // 数组
// 删除cur的children属性,消除children嵌套关系.
delete cur.children;
prev.push(cur, ...subList);
}

return prev;
}, []);
};

const array = tree2Array(tree);
console.log("result", array);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 递归查找,获取children
*/

const getChildren = (data, result, pid) => {
for (const item of data) {
if (item.pid === pid) {
const newItem = { ...item, children: [] };
result.push(newItem);
getChildren(data, newItem.children, item.id);
}
}
};

/**
* 转换方法
*/
const arrayToTree = (data, pid) => {
const result = [];
getChildren(data, result, pid);
return result;
};

console.log("arrayToTree", arrayToTree(arr, 0));

控制台打印