我有这个数据: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 显示每个数据的父级。这里的父级是“Central”、“North”、“East”等。
但是,d.parent.name只是返回无法读取未定义的属性名称。如何使用 acessor 函数获取父级的 name 属性? d.name 返回 child 的 name 属性。
cells
.append('title')
.text(function (d) {
return categoryKey + " : " + d.parent + "\n" + groupKey + " : " + d.name + "\n" + sizeKey + " : " + toCommas(d.value)
});
最佳答案
这里的问题是您正在使用分层数据,并且在一种情况下未定义 d.parent
:层次结构的根节点。不过,修复起来很简单:只需检查父节点是否存在即可:
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
});
您可以使用三元 if-else 将其压缩为一行:
cells
.append('title')
.text(function (d) {
return ( d.parent ? categoryKey + " : " + d.parent.name + "\n" : 'root node' )
+ groupKey + " : " + d.name + "\n" + sizeKey + " : " + toCommas(d.value)
}
(代码未经测试)
关于javascript - 如何使用访问器函数(d)来访问父级的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52418489/