如何使用访问器函数访问父项的值?

时间:2018-09-20 05:56:42

标签: javascript d3.js

我有此数据:https://api.myjson.com/bins/xibvo

cells
  .append('title')
  .text(function (d) {
    return categoryKey + " : " + d.parent.name + "\n" + groupKey + " : " + d.name + "\n" + sizeKey + " : " + toCommas(d.value)
  });

我希望d.parent.name显示每个数据的父级。这里的父母是“中部”,“北部”,“东部”等。

但是,返回的d.parent.name无法读取未定义的属性名称。如何使用acessor函数获取父项的name属性? d.name返回孩子的name属性。

cells
  .append('title')
  .text(function (d) {
    return categoryKey + " : " + d.parent + "\n" + groupKey + " : " + d.name + "\n" + sizeKey + " : " + toCommas(d.value)
  });

如果我使用d.parent,则会得到[object Object]: enter image description here

1 个答案:

答案 0 :(得分:1)

这里的问题是您正在使用层次结构数据,并且在一种情况下未定义public class CrossRef{ [Display(Name = "MANUFACTURER")] [...] public string Manufacturer { get; set; } } // ... gridControl1.DataSource = new BindingList<CrossRef> { new CrossRef() { Manufacturer = ... }, ... }; :层次结构的根节点。修复起来很简单:只需检查父节点是否存在:

d.parent

您可以使用三元if-else将其压缩为一行:

cells
  .append('title')
  .text(function (d) {
    if ( d.parent ) {
      return categoryKey + " : " + d.parent.name + "\n" + groupKey + " : " + d.name + "\n" + sizeKey + " : " + toCommas(d.value)
    }
    return d.name; // or whatever you want to do for the root node case
  });

(未经测试的代码)