js数组扁平化转树例子
时间: 2023-10-20 08:21:25 浏览: 92
js实现树形数据转成扁平数据的方法示例
假设有以下数组:
```js
const arr = [
{ id: 1, name: 'A', parent_id: 0 },
{ id: 2, name: 'B1', parent_id: 1 },
{ id: 3, name: 'B2', parent_id: 1 },
{ id: 4, name: 'C1', parent_id: 2 },
{ id: 5, name: 'C2', parent_id: 2 },
{ id: 6, name: 'C3', parent_id: 3 },
{ id: 7, name: 'D1', parent_id: 4 }
]
```
其中,每个对象代表一个节点,`id` 表示节点的唯一标识,`name` 表示节点的名称,`parent_id` 表示该节点的父节点的 `id`。
现在我们需要将这个数组转成树形结构,即:
```js
const tree = [
{
id: 1,
name: 'A',
children: [
{
id: 2,
name: 'B1',
children: [
{
id: 4,
name: 'C1',
children: [
{
id: 7,
name: 'D1',
children: []
}
]
},
{
id: 5,
name: 'C2',
children: []
}
]
},
{
id: 3,
name: 'B2',
children: [
{
id: 6,
name: 'C3',
children: []
}
]
}
]
}
]
```
实现方式如下:
```js
function flatToTree(arr, id = 0) {
const tree = []
arr.forEach(item => {
if (item.parent_id === id) {
const children = flatToTree(arr, item.id)
if (children.length) {
item.children = children
}
tree.push(item)
}
})
return tree
}
const arr = [
{ id: 1, name: 'A', parent_id: 0 },
{ id: 2, name: 'B1', parent_id: 1 },
{ id: 3, name: 'B2', parent_id: 1 },
{ id: 4, name: 'C1', parent_id: 2 },
{ id: 5, name: 'C2', parent_id: 2 },
{ id: 6, name: 'C3', parent_id: 3 },
{ id: 7, name: 'D1', parent_id: 4 }
]
const tree = flatToTree(arr)
console.log(tree)
```
输出结果:
```js
[
{
id: 1,
name: 'A',
children: [
{
id: 2,
name: 'B1',
children: [
{
id: 4,
name: 'C1',
children: [
{
id: 7,
name: 'D1',
children: []
}
]
},
{
id: 5,
name: 'C2',
children: []
}
]
},
{
id: 3,
name: 'B2',
children: [
{
id: 6,
name: 'C3',
children: []
}
]
}
]
}
]
```
阅读全文