### 写一个函数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}, ] ```
时间: 2024-02-17 13:00:13 浏览: 27
好的,下面是 flatToTree() 函数的实现:
```javascript
function flatToTree(flatArr) {
const tree = [];
// 将节点按照 id 排序
flatArr.sort((a, b) => a.id - b.id);
// 用一个 map 存储每个节点的引用
const nodeMap = new Map();
flatArr.forEach(node => {
node.children = [];
nodeMap.set(node.id, node);
});
// 构建树形结构
flatArr.forEach(node => {
if (node.parent_id === -1) {
tree.push(node);
} else {
const parentNode = nodeMap.get(node.parent_id);
parentNode.children.push(node);
}
});
return tree;
}
```
使用方法如下:
```javascript
const 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},
];
const tree = flatToTree(flatArr);
console.log(JSON.stringify(tree, null, 2));
```
输出结果如下:
```json
[
{
"id": 1,
"title": "A",
"parent_id": -1,
"children": []
},
{
"id": 2,
"title": "B",
"parent_id": -1,
"children": [
{
"id": 3,
"title": "C",
"parent_id": 2,
"children": [
{
"id": 4,
"title": "D",
"parent_id": 3,
"children": []
}
]
}
]
}
]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)