用js把树状结构转换成多为数组
时间: 2024-05-06 13:14:52 浏览: 62
假设你有一个如下的树状结构:
```javascript
const treeData = {
id: 1,
label: 'Node 1',
children: [
{
id: 2,
label: 'Node 2',
children: [
{
id: 4,
label: 'Node 4'
},
{
id: 5,
label: 'Node 5'
}
]
},
{
id: 3,
label: 'Node 3',
children: [
{
id: 6,
label: 'Node 6'
}
]
}
]
};
```
你可以使用递归的方式将其转换成多维数组:
```javascript
function treeToArray(tree) {
const result = [];
if (tree) {
const node = {
id: tree.id,
label: tree.label
};
result.push(node);
if (tree.children) {
tree.children.forEach(child => {
const childrenNodes = treeToArray(child);
result.push(...childrenNodes);
});
}
}
return result;
}
const treeArray = treeToArray(treeData);
console.log(treeArray);
```
输出结果为:
```javascript
[
{ id: 1, label: 'Node 1' },
{ id: 2, label: 'Node 2' },
{ id: 4, label: 'Node 4' },
{ id: 5, label: 'Node 5' },
{ id: 3, label: 'Node 3' },
{ id: 6, label: 'Node 6' }
]
```
这样你就成功将树状结构转换成多维数组了。
阅读全文