【问题标题】:how to check if data is hierarchical in d3.js如何在 d3.js 中检查数据是否分层
【发布时间】:2021-09-08 08:24:42
【问题描述】:

在显示数据之前我要检查它的层次结构 第一个值是我的 def 不是分层的

// no hierarchy
const hierachNo={
  name: "father",
  children: "no",
};



// hierarchy
const hierachJes ={
  name: "father",
  children: [{ name: "Foo" }, { name: "Bar"}]
,
};


d3 hierarchy 方法自动将第一个条目设置为父条目 即使数据不是分层的——只有两个没有深度的条目。
有没有办法检查数据是否分层?

【问题讨论】:

  • 我还没有使用 d3 层次结构,但如果我理解正确的话,它假定一个包含键 namechildren 的结构。所以你的例子是有效的。要检查结构,您可以使用以下内容:var valid = noHirarchy.hasOwnProperty('name') && noHirarchy.hasOwnProperty('children') && Array.isArray(noHirarchy.children)
  • 我添加了一个例子来说明

标签: javascript d3.js data-structures


【解决方案1】:

要检查结构,您可以检查键 namechildren 以及 children 是否是一个数组。

// no hierarchy
const hierachNo = {
  name: "father",
  children: "no",
};

// hierarchy
const hierachYes = {
  name: "father",
  children: [{ name: "Foo" }, { name: "Bar"}]
};

function isHierachy(item) {
  return item.hasOwnProperty('name') && item.hasOwnProperty('children') && Array.isArray(item.children)
}

console.log(isHierachy(hierachNo));
console.log(isHierachy(hierachYes));

【讨论】:

    猜你喜欢
    • 2013-09-12
    • 2011-07-29
    • 2015-05-10
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多