如何将嵌套树形结构转换为React Flow与Dagre可渲染的节点边数组
实现方案
我们直接通过深度优先遍历原始树结构,遍历过程中同步收集节点和边数据即可,无需额外调用父节点查找方法,实现逻辑更简洁高效。
核心逻辑说明
- 每个节点的id为节点对象中除
children属性外的唯一键 - 遍历子节点时天然持有父节点id,可直接生成对应边数据
完整实现代码
// 从单个节点对象中提取节点id const getNodeId = (node) => Object.keys(node).find(key => key !== 'children') /** * 树形结构转React Flow渲染数组 * @param {Object} tree 原始树形结构 * @param {string} edgeType 边的类型,可自定义 * @returns {Array} React Flow所需的节点+边数组 */ function convertTreeToReactFlowData(tree, edgeType = 'default') { const nodes = [] const edges = [] // 递归遍历函数 function traverse(currentNode, parentId = null) { const currentId = getNodeId(currentNode) // 收集当前节点 nodes.push({ id: currentId, // 可选:如果需要显示节点文本,可加data字段 // data: { label: currentNode[currentId] } }) // 存在父节点时生成边 if (parentId) { edges.push({ id: `e${parentId}${currentId}`, source: parentId, target: currentId, type: edgeType, animated: true }) } // 递归遍历子节点 if (Array.isArray(currentNode.children) && currentNode.children.length) { currentNode.children.forEach(childNode => traverse(childNode, currentId)) } } // 从根节点开始遍历 traverse(tree) // 按要求拼接节点在前、边在后的数组返回 return [...nodes, ...edges] } // 使用示例 const tree = { "1": "root", "children": [ { "2": "similar values", "children": [ { "3": "similar values info", "children": [ { "4": "similar values", "children": [ { "5": "similar values", "children": [ { "6": "similar values" } ] } ] } ] } ] } ] } const result = convertTreeToReactFlowData(tree) console.log(result) // 输出与你要求的目标格式完全一致
内容的提问来源于stack exchange,提问作者r342346
相关产品推荐
相关产品推荐

