问题描述
我正在努力在这个 json 代码中找到孩子们的孩子,任何帮助将不胜感激! 基本上我在 D3 中有一个 3 层森伯斯特图表,我想突出显示当前悬停的节点,以及它的子节点和外环子节点。当前代码有效,但仅突出显示最近的孩子:
function getChildren(node){
var children = [];
children.push(node);
//iterate through the children
node.children.forEach(function(child){
//add to the child list if target id is not same
children.push(child);
children.push(child.children);
////Below is my attempt to add second layer of child elements but it isn't working as planned:
child.children.forEach(function(innerChild){
if (innerChild.children) {
children.push(innerChild.children);
}
});
});
return children
}
层次结构如下:
result = _(dataArr)
.groupBy(x => x["Inner circle"])
.map((value1,key) => ({
name: key,count: sum(value1),children: _(value1)
.groupBy(x => x["Middle circle"])
.map((value2,key) => ({
name: key,count: sum(value2),children: _(value2)
.groupBy(x => x["Outer circle"])
.map((value3,key) => ({
name: key,count: sum(value3),children: _(value3)
.groupBy(x => x["Label"])
.map((value4,key) => ({ name: key,count: outersum(value4),children: [] }))
.value()
}))
.value()
}))
.value()
}))
.value();
解决方法
在当前状态下,您有 2 层深。因此缺少外圈。
children.push(node);
将 json 对象完整地添加到 children
数组中。
children.push(child);
将 json 对象的所有子项添加到 children
数组。这是第一层或内层。
children.push(child.children);
添加内圈的所有孩子。所以这是第二层。
缺少的代码,在上一行之后添加:
child.children.forEach(function(innerChild){
if (innerChild.children) {
children.push(innerChild.children);
}
});
会将第三层添加到您的数组中。