Angular中如何根据ID将对象插入嵌套树形数组指定位置
Angular嵌套树形数组指定位置插入节点实现方案
针对树形视图的嵌套数组操作,直接用递归深度优先遍历匹配目标节点即可,无需引入额外依赖。
1. 类型定义
先对齐业务中用到的TreeNode类型:
interface TreeNode { name: string; id: string | number; children?: TreeNode[]; }
2. 通用插入工具函数
函数会递归遍历所有层级的节点,匹配到目标ID后直接将待插入对象追加到对应节点的children数组末尾,同时兼容目标节点初始没有children属性的场景:
function insertNodeToTree( treeData: TreeNode[], targetId: string | number, insertNode: TreeNode ): boolean { for (const node of treeData) { // 匹配到目标节点 if (node.id === targetId) { node.children = node.children ?? []; node.children.push(insertNode); return true; } // 存在子节点则递归向下查找 if (node.children?.length) { const isInserted = insertNodeToTree(node.children, targetId, insertNode); if (isInserted) return true; } } // 遍历完所有节点未找到目标ID return false; }
3. 调用示例
对应给出的业务场景,直接传入参数调用即可:
const TREE_DATA: TreeNode[] = [{"name":"Demo","id":"demo_1","children":[{"name":"Folder","id":"folder_1","children":[{"name":"File","id":1},{"name":"Doc","id":2}]},{"name":"Folder 2","id":"folder_2","children":[{"name":"doc file","id":3},{"name":"word","id":4}]}]},{"name":"Projects","id":"pro_1","children":[{"name":"Dir","id":"dir_1","children":[{"name":"ib","id":5},{"name":"Pro 2","id":6}]}]}] const obj: TreeNode = { name: 'information', id: 50 } // 定位到id为dir_1的节点,插入obj insertNodeToTree(TREE_DATA, 'dir_1', obj);
执行完成后TREE_DATA的结构和预期结果完全一致。
补充说明
- 上述实现会直接修改原始数组,如果业务要求不可变数据,可在遍历前对树结构做深拷贝后再操作。
- 如果需要插入到
children的指定位置而非末尾,将push替换为splice方法传入对应索引即可,例如插入到首位:node.children.splice(0, 0, insertNode)。 - 常规业务场景下(节点数在万级以内)递归遍历的性能完全满足需求,如果是超大规模树结构可改为栈实现的非递归遍历,避免递归栈溢出。
内容的提问来源于stack exchange,提问作者Dinesh Kumar
相关产品推荐
相关产品推荐

