I am using d3.nest()
to convert flat JSON files into hierarchical trees. This works just fine if you know in advance the levels that found in your data: d3.nest()
creates a nesting-level for each key function you pass it.
However, I would like to know if there is an elegant way to dynamically pass key functions. This might be an elementary question, but my Javascript skills are also elementary.
This is a static example working with key names stored in an array:
var levels = ['first', 'second', 'third']
var root = {
"key":"root",
"values":
d3.nest()
.key(function(d){ return d[levels[0]] })
.key(function(d){ return d[levels[1]] })
.key(function(d){ return d[levels[2]] })
.entries(data)
}
My solution now is an if-else loop that pseudo-dynamically creates different nestings:
// build the nested tree pseudo-dynamically
if (levels.length === 1) {
var nest = d3.nest()
.key(function(d){return d[levels[0]]})
.entries(data);
} else if (levels.length === 2) {
var nest = d3.nest()
.key(function(d){return d[levels[0]]})
.key(function(d){return d[levels[1]]})
.entries(data);
} else if (levels.length === 3) {
var nest = d3.nest()
.key(function(d){return d[levels[0]]})
.key(function(d){return d[levels[1]]})
.key(function(d){return d[levels[2]]})
.entries(data);
}
[...]
Is there an elegant way to dynamically pass keys to d3.nest()
? What I would like is something in principle like the following example (which DOES NOT WORK):
var root = {
"key":"root",
"values":
d3.nest()
for (var i = 0; i < levels.length; i++) {
.key(function(d){return d[levels[i]]})
}
.entries(data)
}
Thanks for your time!