数组转树形数据

const nodes = [
    { id: 3, name: '节点C', pid: 1 },
    { id: 6, name: '节点F', pid: 3 },
    { id: 0, name: 'root', pid: null },
    { id: 1, name: '节点A', pid: 0 },
    { id: 8, name: '节点H', pid: 4 },
    { id: 4, name: '节点D', pid: 1 },
    { id: 2, name: '节点B', pid: 0 },
    { id: 5, name: '节点E', pid: 2 },
    { id: 7, name: '节点G', pid: 2 },
    { id: 9, name: '节点I', pid: 5 }
];

function convert(data) {
    if (!Array.isArray(data)) {
        new Error('data must be an array');
        return;
    }

    let result;
    let map = {};
    data.forEach(item => {
        //id作为key
        map[item.id] = item;
    });
    data.forEach(item => {
        // item.pid 为0时 返回underfined
        let parent = map[item.pid];
        if (parent) {
            //如果用children,就直接push,没有就初始化数组
            (parent.children || (parent.children = [])).push(item);
        } else {
            // 这里push的item是pid为0的数据
            result = item;
        }
    });
    return result;
}

console.log(convert(nodes));
{
    id: 0,
    name: 'root',
    pid: null,
    children: [
      { id: 1, name: '节点A', pid: 0, children: [Array] },
      { id: 2, name: '节点B', pid: 0, children: [Array] }
    ]
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
获取树形数据的递归算法可以使用深度优先遍历(DFS)或广度优先遍历(BFS)。以下是使用 DFS 的实现示例: ```javascript function getTreeList(treeData, parentId = null) { const result = []; for (let i = 0; i < treeData.length; i++) { const node = treeData[i]; if (node.parentId === parentId) { const children = getTreeList(treeData, node.id); if (children.length) { node.children = children; } result.push(node); } } return result; } ``` 其中,`treeData` 是原始的树形数据,`parentId` 是当前节点的父节点 ID。首先创建一个空数组 `result`,然后遍历原始数据,找到所有父节点 ID 为当前节点 ID 的子节点,并递归获取子节点的子节点,直到没有子节点为止。如果当前节点有子节点,则将子节点数组添加到当前节点的 `children` 属性中,最后将当前节点添加到 `result` 数组中并返回。 使用示例: ```javascript const treeData = [ { id: 1, name: 'Node 1', parentId: null }, { id: 2, name: 'Node 2', parentId: 1 }, { id: 3, name: 'Node 3', parentId: 1 }, { id: 4, name: 'Node 4', parentId: 2 }, { id: 5, name: 'Node 5', parentId: 3 }, { id: 6, name: 'Node 6', parentId: null }, { id: 7, name: 'Node 7', parentId: 6 }, ]; const treeList = getTreeList(treeData); console.log(treeList); ``` 输出结果: ``` [ { "id": 1, "name": "Node 1", "parentId": null, "children": [ { "id": 2, "name": "Node 2", "parentId": 1, "children": [ { "id": 4, "name": "Node 4", "parentId": 2 } ] }, { "id": 3, "name": "Node 3", "parentId": 1, "children": [ { "id": 5, "name": "Node 5", "parentId": 3 } ] } ] }, { "id": 6, "name": "Node 6", "parentId": null, "children": [ { "id": 7, "name": "Node 7", "parentId": 6 } ] } ] ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值