[英]How to build a tree json in javascript
我在玩D3图表。 他们提供的示例之一是绘制树形结构的图表( https://observablehq.com/@d3/tidy-tree )
我按照此示例将这张图表并嵌入到Power BI中( https://azurebi-docs.jppp.org/powerbi-visuals/d3js.html?tabs=docs%2Cdocs-open#sample ),但遇到了麻烦我目前拥有的数据。 该图表使用json作为输入( https://raw.githubusercontent.com/d3/d3-hierarchy/v1.1.8/test/data/flare.json )。 生成此类树结构json的脚本如下:
function toJSON(data) {
var flare = { name: "ROOT", children: [] },
levels = ["parentname","categoryname", "categoryname"];
// For each data row, loop through the expected levels traversing the output tree
data.forEach(function(d){
// Keep this as a reference to the current level
var depthCursor = flare.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({ name : d.product, size : d.revenue });
});
});
// End of conversion
return flare;
}
我面临的问题是我的数据具有不同的结构...该脚本假定level变量包含所有级别。 但是我的数据结构是这样的,每行都有一个名称(即CategoryName)和指向父表的指示符(即同一表中的ParentName)。 如此有效的记录是
CategoryName | ParentName
Category 1
Category 2 | Category 1
Category 3 | Category 2
Category 4 | Category 2
我应该如何修改提供的javascript以根据当前的数据结构构建json?
感谢您可以提供的任何支持或推荐。
数据格式为:
data = [
{categoryname: 'Category 1', parentname: 'null'},
{categoryname: 'Category 2', parentname: 'Category 1'},
{categoryname: 'Category 3', parentname: 'Category 2'},
{categoryname: 'Category 4', parentname: 'Category 2'},
];
整个PowerBI D3脚本如下所示:
/*
* All D3 visuals run in a frame with the following elements/variables:
*
* SVG element:
* - <svg xmlns="http://www.w3.org/2000/svg" class="chart" id="chart" >
*
* pbi object:
* - 'dsv' : function that retrieves the data via the provided callback: pbi.dsv(callback)
e.g. pbi.dsv(function(data) { //Process data function });
* - 'height' : height of the sandbox frame
* - 'width' : width of the sandbox frame
* - 'colors' : color array with 8 colors; changable via options
*
* Code is based on: https://bl.ocks.org/mbostock/4339083
*/
// ADD: translate function for the data
function toJSON(data) {
var flare = { name: "ROOT", children: [] },
levels = ["parentname","categoryname", "categoryname"];
// For each data row, loop through the expected levels traversing the output tree
data.forEach(function(d){
// Keep this as a reference to the current level
var depthCursor = flare.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({ name : d.product, size : d.revenue });
});
});
// End of conversion
return flare;
}
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = pbi.width - margin.left - margin.right, // ALTER: Changed fixed width with the 'pbi.width' variable
height = pbi.height - margin.top - margin.bottom; // ALTER: Changed fixed height with the 'pbi.height' variable
var i = 0,
duration = 750,
root;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
var svg = d3.select("#chart") // ALTER: Select SVG object; no need to create it
.attr("width", width + margin.left + margin.right) // ALTER: Add complete width
.attr("height", height + margin.top + margin.bottom) // ALTER: Add complete height
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// ALTER: Replaced the d3.json function with the pbi variant: pbi.dsv
pbi.dsv(function(data) {
var flare = toJSON(data); // ALTER: add extra convertion step to parent/child JSON
root = flare;
root.x0 = height / 2;
root.y0 = 0;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
root.children.forEach(collapse);
update(root);
});
d3.select(self.frameElement).style("height", height + margin.top + margin.bottom);
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 180; });
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.on("click", click);
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? pbi.colors[0] : pbi.colors[1]; });
nodeEnter.append("text")
.attr("x", function(d) { return d.children || d._children ? -10 : 10; })
.attr("dy", ".35em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.name; })
.style("fill-opacity", 1e-6);
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeUpdate.select("circle")
.attr("r", 4.5)
.style("fill", function(d) { return d._children ? pbi.colors[0] : pbi.colors[1]; });
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Update the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
在我看来,您的问题是XY问题的另一种情况:您不是在询问层次结构本身的问题,而是在询问您认为对于创建该层次结构所必需的功能。
您不需要该功能即可创建层次结构。 根据您的数据,您可以只使用d3.stratify
:
const csv = `CategoryName,ParentName Category 1, Category 2,Category 1 Category 3,Category 2 Category 4,Category 2`; const data = d3.csvParse(csv); const stratify = d3.stratify() .id(function(d) { return d.CategoryName; }) .parentId(function(d) { return d.ParentName; }); let root = stratify(data); console.log(root)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
由于您已经解析了数据,因此更加容易:
const data = [{ categoryname: 'Category 1', parentname: '' }, { categoryname: 'Category 2', parentname: 'Category 1' }, { categoryname: 'Category 3', parentname: 'Category 2' }, { categoryname: 'Category 4', parentname: 'Category 2' }, ]; const stratify = d3.stratify() .id(function(d) { return d.categoryname; }) .parentId(function(d) { return d.parentname; }); let root = stratify(data); console.log(root)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
PS:使用浏览器的控制台检查root
对象,而不是检查堆栈片段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.