【发布时间】:2019-08-17 12:55:29
【问题描述】:
我正在尝试在 D3v4 中创建一个可折叠的树形图,例如 this。我将数据作为 JSON 对象数组,需要将数据准备成分层树结构。
我的数据如下所示:
[
{
"ingoingBatch": "BC1",
"process": "API",
"outgoingBatch": "CD1",
"counterIndex": "5"
},
{
"ingoingBatch": "BC2",
"process": "API",
"outgoingBatch": "CD1",
"counterIndex": "6"
},
{
"ingoingBatch": "AB1",
"process": "PUR",
"outgoingBatch": "BC1",
"counterIndex": "1"
},
{
"ingoingBatch": "AB2",
"process": "PUR",
"outgoingBatch": "BC1",
"counterIndex": "2"
},
{
"ingoingBatch": "AB3",
"process": "PUR",
"outgoingBatch": "BC2",
"counterIndex": "3"
},
{
"ingoingBatch": "AB4",
"process": "PUR",
"outgoingBatch": "BC2",
"counterIndex": "4"
}
]
我想要的结构类似于this structure
我尝试创建一个JSfiddle,您可以在其中看到第 129-142 行的原始数据。我在第 11-115 行插入了我自己的数据,并使用了第 117-126 行的here 中的函数 d3 函数嵌套:
var entries = d3.nest()
.key(function(d) { return d.ingoingBatch; })
.key(function(d) { return d.outgoingBatch; })
.entries(json);
console.log(entries);
var treeData = d3.hierarchy(entries);
console.log(treeData);
我认为问题出在数据准备中。当我使用我的数据运行 JSfiddle 时收到的错误消息是:
TypeError: root.children is undefined
根节点应该是C1,结构应该是这样的:
C1
B2 B1
A1 A2 A3 A4
节点之间的链接是ingingBatch 和outingBatch。 任何人都可以帮助准备我的数据以使我的数据准备恰到好处吗?
------------更新-----------
如果我使用此处this question 的答案,我会更接近于拥有正确的数据结构。当我代替这个时:
var entries = d3.nest()
.key(function(d) { return d.ingoingBatch; })
.key(function(d) { return d.outgoingBatch; })
.entries(json);
console.log(entries);
var treeData = d3.hierarchy(entries);
console.log(treeData);
使用其他问题的答案并使用此功能:
var newData = { name :"root", children : [] },
levels = ["outgoingBatch"];
// levels = ["ingoingBatch","outgoingBatch"];
// For each data row, loop through the expected levels traversing the output tree
json.forEach(function(d){
// Keep this as a reference to the current level
var depthCursor = newData.children;
// Go down one level at a time
levels.forEach(function( property, depth ){
// Look to see if a branch has already been created
var index;
depthCursor.forEach(function(child,i){
if ( d[property] == child.name ) index = i;
});
// Add a branch if it isn't there
if ( isNaN(index) ) {
depthCursor.push({ name : d[property], children : []});
index = depthCursor.length - 1;
}
// Now reference the new child array as we go deeper into the tree
depthCursor = depthCursor[index].children;
// This is a leaf, so add the last element to the specified branch
if ( depth === levels.length - 1 ) depthCursor.push({ outgoingBatch : d.outgoingBatch });
});
});
var treeData = newData
console.log(treeData);
我得到一个三图。但它的结构不正确,因为 CD1 没有设置为根节点,而是设置为子节点之一。
【问题讨论】:
标签: javascript d3.js