Rename the key and values ​​in d3.nest ()

Learn JS Data and gives an example of split-apply-comb 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));

that leads to

[{"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 simple way to convert the output from the socket, so it keyhas its own name and is valuessmoothed, creating 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 violin is difficult to generalize.

+4
source share
1 answer

There is no way to d3.nest()do this (at least not in version 3, there is a slight chance that it was added in v4, but I doubt it).

But you can 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
    }
  });

, , , , ( key = > , ):

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;
  });
+6

All Articles