Json d3访问每个对象 [英] Json d3 access each object
问题描述
{
name:Max,
value:107,
children:[
{
name:Don,
value:60,
children[
{name:CC,value:25} b $ b {name:Jim,value:35}
]
},
{
name:David,
value:47,
children:[
{name:Jeff,value:32},
{name:Buffy :15}
]
}
]
}
如何使用d3访问最内层的子名称?
我试过:
.text(function(d){return d.children?null:d.name;});
但它无效....
当我做
.text(function(d){return d.name});
它只显示外层循环的名称 - > Don,David。
d3.json('flare.json',function(data){
var canvas = d3.select('p1' )
.append('svg')
.attr('width',800)
.attr('height',800)
var color = d3 .scale.category20c();
var data1 = data.children;
canvas.selectAll('text')
.data(data1)
.enter()
.append('text')
.attr('x',function(d){return 2;})
.attr('y',function d,i){return i * 15;})
.attr('fill','black')
.style('font-size','12px')
.text (function(d){return d.children?null:d.name;})
在↓↓之前
{
name:Don,
value:75 ,
children[
{name:CC,value:25},
{name:Jim,value:35} $ b]
}
当数据采用这种单一嵌套格式时,
你需要一个递归函数 -
$ / p> function getNames(d){
return d.children? d.children.map(getNames):d.name;
}
这将返回一个嵌套列表, 。
{
"name": "Max",
"value": 107,
"children": [
{
"name": "Don",
"value": 60,
"children" [
{"name": "CC", "value": 25},
{"name": "Jim", "value": 35}
]
},
{
"name": "David",
"value": 47,
"children": [
{"name": "Jeff", "value": 32},
{"name": "Buffy", "value": 15}
]
}
]
}
How can I access the inner most child name with d3?
I tried doing :
.text(function (d) { return d.children ? null : d.name; });
But it didn't work....
When I do
.text(function (d) { return d.name });
it only shows the name of the outer loop --> Don, David.
d3.json('flare.json', function (data) {
var canvas = d3.select('p1')
.append('svg')
.attr('width', 800)
.attr('height', 800)
var color = d3.scale.category20c();
var data1 = data.children;
canvas.selectAll('text')
.data(data1)
.enter()
.append('text')
.attr('x', function (d) { return 2; })
.attr('y', function (d, i) { return i * 15; })
.attr('fill', 'black')
.style('font-size', '12px')
.text(function (d) { return d.children ? null: d.name; })
Data I had before ↓ ↓
{
"name": "Don",
"value": 75,
"children" [
{"name": "CC", "value": 25},
{"name": "Jim", "value": 35}
]
}
When the data was in this single nested format, my code worked perfectly, but when I did double nest on it, it no longer works
You need a recursive function for this --
function getNames(d) {
return d.children ? d.children.map(getNames) : d.name;
}
This will return a nested list with the names of the elements that have no children.
这篇关于Json d3访问每个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!