复盘一道面试中写的不好的场景题
题目描述
写一个函数flatToTree(),将扁平化数据转成json树形结构
实例输入
let flatArr = [
{id: 1, title: "A", parent_id: -1},
{id: 2, title: 'B', parent_id: -1},
{id: 3, title: 'C', parent_id: 2},
{id: 4, title: 'D', parent_id: 3},
]
(元素自身id唯一,pid是父节点。父节点为-1的为根节点,可以有多个根节点)
思路
通过遍历完成两个任务
1、创建一个新的带children的结构
2、父节点在map有key值对应,则在父节点的children添加新元素
没有父节点,在根节点添加父节点
代码
function ArrToTree(arr) {
let tree = [];
const map = {};
for (let item of arr) {
map[item.id] = {
...item,
children: [],
};
}
for (let item of arr) {
let newItem = map[item.id];
if (map[item.pid]) {
let parent = map[item.pid];
parent.children.push(newItem);
} else {
tree.push(newItem);
}
}
return tree;
}
输出结果
[
{ id: 1, title: 'A', pid: -1, children: [] },
{ id: 2, title: 'B', pid: -1, children: [
{ id: 3, title: 'C', pid: 2, children: [
{ id: 4, title: 'D', pid: 3, children: [] }]
} ]
}
]