Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename key and values in d3.nest()

Learn JS Data gives and example of split-apply-combine with

var expenseMetrics = d3.nest()
  .key(function(d) { return d.name; })
  .rollup(function(v) { return {
    count: v.length,
    total: d3.sum(v, function(d) { return d.amount; }),
    avg: d3.mean(v, function(d) { return d.amount; })
  }; })
  .entries(expenses);
console.log(JSON.stringify(expenseMetrics));

which results in

[{"key":"jim","values":{"count":2,"total":79,"avg":39.5}},
 {"key":"carl","values":{"count":1,"total":120.11,"avg":120.11}},
 {"key":"stacy","values":{"count":3,"total":90.9,"avg":30.3}}]

Is there any easy way to transform the output from nest such that the key has a custom name and values is flattened, producing an output like

[{"name":"jim","count":2,"total":79,"avg":39.5},
 {"name":"carl","count":1,"total":120.11,"avg":120.11},
 {"name":"stacy","count":3,"total":90.9,"avg":30.3}]

This question seems related but the solution in the provided fiddle is hard to generalize.

like image 773
ARM Avatar asked May 11 '16 19:05

ARM


1 Answers

There's no way to have d3.nest() do it (at least not in version 3; there's a slight chance it got added in v4, but I doubt it).

But you can certainly do it like this:

var expenseMetrics = d3.nest()
  ...
  .entries(expenses)
  .map(function(group) {
    return {
      name: group.key,
      count: group.values.count,
      total: group.values.total,
      avg:   group.values.avg
    }
  });

If you want it to be more general, you can get the same output as above without hardcoding anything (except the key => name mapping, which is appropriate to hardcode anyway):

var expenseMetrics = d3.nest()
  ...
  .entries(expenses)
  .map(function(group) {
    var merged = { name: group.key };

    // Copy each key-val pair of group.values into merged
    Object.keys(group.values).forEach(function(key) {
      merged[key] = group.values[key];
    });

    return merged;
  });
like image 200
meetamit Avatar answered Oct 20 '22 00:10

meetamit