12.扁平数组->树形结构:
参考视频
let arr = [
{ id: 1, name: '部门1', parent_id: 0 },
{ id: 2, name: '部门2', parent_id: 1 },
{ id: 3, name: '部门3', parent_id: 1 },
{ id: 4, name: '部门4', parent_id: 3 },
{ id: 5, name: '部门5', parent_id: 4 },
]
function convert(arr) {
const result = [];
// 转为键值对形式 {1: { id: 1, name: '部门1', parent_id: 0 }}
// pre:累加 , cur:当前数组中的元素 , {}:初始值为对象
const map = arr.reduce((pre, cur) => {
pre[cur.id] = cur;
return pre;
}, {});
// 遍历数组中的每一个对象,如 {id:1} 、 {id:2}
for (const item of arr) {
if (item.parent_id === 0) {
// 当p_id=0时,将其直接插入到数组中
result.push(item);
continue;
}
// 如果p_id在map中
if (item.parent_id in map) {
// 新建parent,比如表示id:1是父节点
const parent = map[item.parent_id];
// parent.children 初始时为空[]
parent.children = parent.children || [];
// 将array中的每一项插入到对应的子元素中
parent.children.push(item);
}
}
return result;
}
const res = convert(arr);
console.log(res);
树形结构->扁平数组
let arr = [
{
id: 1,
title: '节点1',
parent_id: 0,
children: [
{
id: 2,
title: '节点1_1',
parent_id: 1
}
]
}
]
function convertToArr(arr) {
return arr.reduce((pre, cur) => {
const { id, title, parent_id, children = [] } = cur;
return pre.concat([{ id, title, parent_id, }], convertToArr(children));
}, []);
}
const res = convertToArr(arr);
console.log(res);