Skip to content

Instantly share code, notes, and snippets.

@beemyfriend
Last active November 24, 2018 00:18
Show Gist options
  • Save beemyfriend/b9b0a013362bfc0cefa43f7bbb8d403d to your computer and use it in GitHub Desktop.
Save beemyfriend/b9b0a013362bfc0cefa43f7bbb8d403d to your computer and use it in GitHub Desktop.
How do I loop through JSON objects in D3?
<head></head>
<body></body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var data = [
{
"name": "Sample 1",
"embed": 10,
"interactive": 10,
"rapidDev": 7,
"support": 7,
"predictive": 4,
"modelDev": 3,
"cost": 2
},
{
"name": "Sample 2",
"embed": 7,
"interactive": 6,
"rapidDev": 7,
"support": 7,
"predictive": 4,
"modelDev": 3,
"cost": 10
},
{
"name": "Sample 3",
"embed": 10,
"interactive": 10,
"rapidDev": 2,
"support": 2,
"predictive": 2,
"modelDev": 2,
"cost": 10
},
{
"name": "Sample 4",
"embed": 2,
"interactive": 7,
"rapidDev": 7,
"support": 7,
"predictive": 10,
"modelDev": 3,
"cost": 8
}
];
var tools = ['embed', 'interactive', 'rapidDev', 'support', 'predictive', 'modelDev', 'cost']
var width = 1000,
height = 600;
var toolRadii = d3.scaleOrdinal()
.domain(['embed', 'interactive', 'rapidDev', 'support', 'predictive', 'modelDev', 'cost'])
.range([[10, 20], [20, 30], [30, 40], [40, 50], [50, 60], [60, 70],
[70, 80]]);
var gLocator = d3.scaleOrdinal()
.domain([0, 1, 2, 3])
.range([[width/4, height/4], [width * 3/4, height/4], [width/4, height* 3/4], [width * 3/4, height * 3/4]]);
function donuts(d, tool){
var temp = d3.arc()
.innerRadius(toolRadii(tool)[0])
.outerRadius(toolRadii(tool)[1])
.startAngle(0)
.endAngle(Math.PI * 2 * d[tool]/10);
return temp();
}
var svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height);
var g = svg.selectAll('g')
.data(data)
.enter().append('g')
.attr('width', width/2)
.attr('height', height/2)
.attr('transform', function(d,i){return 'translate(' + gLocator(i)[0] + ',' + gLocator(i)[1] + ')'});
function path_tool(tool){
g.append('path')
.attr('d', function(d){return donuts(d, tool)});
}
tools.map(function(x){path_tool(x)});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment