如何用组和汇总替换 d3js 嵌套函数

Max*_*Max 5 javascript data-structures d3.js

我正在努力将一些较旧的 d3js 代码转换为最新版本 (V6)。似乎旧功能nest()已被弃用。从现在开始,文档推荐使用group()and rollup(),但是,他们没有给出任何真正好的例子,我很难用这些新函数实现相同的数据结构。

数据输入:

[
  {
    name: "Anton",
    year: "1990"
  },
  {
    name: "Anton",
    year: "1990"
  },
  {
    name: "Anton",
    year: "1971"
  },
  {
    name: "Markus",
    year: "1981"
  },
]
Run Code Online (Sandbox Code Playgroud)

旧 D3 代码:

let nested = d3.nest()
  .key(function (d) { return d.name })     
  .key(function (d) { return d.year })
  .rollup(function (leaves) { return leaves.length })
  .entries(data)
Run Code Online (Sandbox Code Playgroud)

输出(正确):

[
  {
    key: "Anton"
    values: [
      {
        key: "1990",
        value: 2
      }
      {
        key: "1971",
        value: 1
      }
    ]  
  },
  {
    key: "Markus"
    values: [
      key: "1981"
      value: 1
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

新代码

我试图合并group,并rollup以不同的方式,但我总是用另一种数据结构结束。我来的关闭是这样的:

let rollup = d3.rollups(data, v => v.length, d => d.name, d => d.year);
let arrayFromRollup = Array.from(rollup, ([key, value]) => ({key, value}));
Run Code Online (Sandbox Code Playgroud)

输出(错误)

[
  {
    key: "Anton"
    values: [
      ["1990", 2],
      ["1971", 1]
    ]  
  },
  {
    key: "Markus"
    values: [
      ["1981", 1]
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

我对任何建议都有帮助,显然,我发现的大多数类似问题/帖子都很旧并且使用nest.

Rub*_*oot 8

D3 提供了出色的便利功能,但随着 ES6 的兴起,数组和对象操作变得更加容易。您可以使用纯 ES6 方法来实现此目的:

const input = [{
    name: "Anton",
    year: "1990"
  },
  {
    name: "Anton",
    year: "1990"
  },
  {
    name: "Anton",
    year: "1971"
  },
  {
    name: "Markus",
    year: "1981"
  },
]

const expected = [
  {
    key: "Anton",
    values: [
      {
        key: "1990",
        value: 2
      },
      {
        key: "1971",
        value: 1
      }
    ],
  },
  {
    key: "Markus",
    values: [
      {
        key: "1981",
        value: 1,
      }
    ],
  },
];

// For ease of use, start with an object, we map key to values
// and unpack it later. The structure we go for now:
// { name: { year: count }}
const nameYearsCount = input.reduce((obj, {
  name,
  year
}) => {
  if (!(name in obj)) {
    obj[name] = {
      [year]: 1
    };
  } else {

    // I.e. if the year doesn't exist, default to zero
    obj[name][year] = (obj[name][year] || 0) + 1
  }
  return obj;
}, {});

// Now transform it into the desired format
const result = Object.entries(nameYearsCount)
  .map(([name, yearsCount]) => {
    const values = Object.entries(yearsCount)
      .map(([year, count]) => ({
        key: year,
        value: count
      }));
    return {
      key: name,
      values
    };
  });

console.log(result);
Run Code Online (Sandbox Code Playgroud)