You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在D3.js中检测待渲染数据是否为合法层级结构

层级结构合法性检测实现

你可以通过递归校验节点规则的方式实现精准检测,符合你给出的判定标准的检测逻辑如下:

  • 单个节点必须为非空对象
  • 若节点携带children属性,该属性值必须为数组,且数组内所有子节点同样符合上述节点规则

检测代码实现

function isValidHierarchy(node) {
  // 校验当前节点是否为合法非空对象
  if (typeof node !== 'object' || node === null) return false
  // 校验children属性规则
  if ('children' in node) {
    // children必须为数组类型
    if (!Array.isArray(node.children)) return false
    // 递归校验所有子节点合法性
    for (const child of node.children) {
      if (!isValidHierarchy(child)) return false
    }
  }
  return true
}

测试用例验证

// 非法层级结构测试
const hierachNo = {
  name: "father",
  children: "no",
};
console.log(isValidHierarchy(hierachNo)) // 输出 false

// 合法层级结构测试
const hierachJes = {
  name: "father",
  children: [{ name: "Foo" }, { name: "Bar"}]
};
console.log(isValidHierarchy(hierachJes)) // 输出 true

你可以在调用d3.hierarchy方法之前先调用该函数做前置校验,只有返回true的合法结构再传入D3处理即可避免异常结果。

内容的提问来源于stack exchange,提问作者Sator

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 22:54:01