d3.js v7下将数组转换为层级结构实现可点击tidy tree图表
D3.js v7 层级嵌套数据转换方案
原代码问题排查
- 遍历逻辑错误:原代码将每行的单个元素作为独立路径处理,没有将整行元素按顺序作为完整层级路径遍历,无法生成正确的父子关联
- 字段名不匹配:生成节点时直接用变量e作为键名,最终生成的节点键是
e而非要求的name - 冗余逻辑:输入数据的每个元素本身就是分层节点,不需要执行
split('/')拆分路径
实现代码
const sampleInput = [['x',2,3,'a'],['x',2,4,'b'],['y',1,3,'a']]; const result = []; sampleInput.forEach(path => { let currentLevel = result; path.forEach((nodeName, index) => { // 统一转为字符串避免数字和字符串类型的同名节点判定为不同 const name = String(nodeName); // 查找当前层级是否已存在同名节点 const existNode = currentLevel.find(item => item.name === name); if (!existNode) { const newNode = { name }; // 非路径最后一级的节点添加children字段 if (index < path.length - 1) { newNode.children = []; } currentLevel.push(newNode); currentLevel = newNode.children || []; } else { // 已有节点直接进入下一层级 currentLevel = existNode.children || []; } }) })
输出说明
执行后result变量即为符合d3.tidy tree要求的层级结构,根节点包含name和children字段,叶子节点无多余children字段,可直接传入d3.hierarchy()生成可用于绘图的层级实例。
内容的提问来源于stack exchange,提问作者nama asliku
相关产品推荐
相关产品推荐

