如何获取数组的键或 属性 值

How to get key of array or property value

使用D3,是否可以找到特定值的键?

例如,假设使用以下数组,我想 return redDelicious(实际上是 "Red Delicious")并且我使用的是值 d.y:

[
  { year: "2006", redDelicious: "10", mcintosh: "15", oranges: "9", pears: "6" },
  { year: "2007", redDelicious: "12", mcintosh: "18", oranges: "9", pears: "4" },
  { year: "2008", redDelicious: "05", mcintosh: "20", oranges: "8", pears: "2" },
  { year: "2009", redDelicious: "01", mcintosh: "15", oranges: "5", pears: "4" },
  { year: "2010", redDelicious: "02", mcintosh: "10", oranges: "4", pears: "2" },
  { year: "2011", redDelicious: "03", mcintosh: "12", oranges: "6", pears: "3" },
  { year: "2016", redDelicious: "19", mcintosh: "17", oranges: "5", pears: "7" },
]

此外,是否可以在一个键中包含多个词并仍然在 D3/JS 中引用它?例如,假设我希望密钥为 "Red Delicious" 而不是 "redDelicious"

  var data = [
      { year: "2006", red Delicious: "10", mcintosh: "15", oranges: "9", pears: "6" },
      { year: "2007", red Delicious: "12", mcintosh: "18", oranges: "9", pears: "4" },
      { year: "2008", red Delicious: "05", mcintosh: "20", oranges: "8", pears: "2" },
      { year: "2009", red Delicious: "01", mcintosh: "15", oranges: "5", pears: "4" },
      { year: "2010", red Delicious: "02", mcintosh: "10", oranges: "4", pears: "2" },
      { year: "2011", red Delicious: "03", mcintosh: "12", oranges: "6", pears: "3" },
      { year: "2016", red Delicious: "19", mcintosh: "17", oranges: "5", pears: "7" },
    ]

更新: 最后一行,我想引用红色美味,但它 returns 苹果:未定义。这是一个 jsfiddle 来显示我遇到的问题(鼠标悬停时数据显示为 "undefined")。

var rect = groups.selectAll("rect")
      .data(function(d) { return d; })
      .enter()
      .append("rect")
      .attr("x", function(d) { return x(d.x); })
      .attr("y", function(d) { return y(d.y0 + d.y); })
      .attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); })
      .attr("width", x.rangeBand())
      .on("mouseover", function() { tooltip.style("display", null) })
      .on("mouseout", function() { tooltip.style("display", "none"); })
      .on("mousemove", function(d) {
        var xPosition = d3.mouse(this)[0] - 15;
        var yPosition = d3.mouse(this)[1] - 25;
        tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");

        tooltip.select("text").text("Apple: "+d['red Delicious']);
      });

理想情况下,我还希望能够获取正在绘制的当前值并找到它的键(红色美味),使其类似于

.text(d.key+": "+d.y) // where d.key is the correct way to find d's key

当您创建要传递给 d3.layout.stack() 布局的转换数据集时,您丢失了与每个数据点对应的水果名称的信息。

如果您 console.log(dataset) 您会看到它是一个包含 4 个数组的数组,每个数组对应一个水果,每个数组由表示数据点的 x 和 y 值的对象组成。您还需要跟踪水果:

var dataset = d3.layout.stack()(["red Delicious", "mcintosh", "oranges", "pears"].map(function(fruit) {
  return data.map(function(d) {
      return {x: parse(d.year), y: +d[fruit], "fruit":fruit};
  });
}));

稍后在您的工具提示文本中,您可以参考 d['fruit']

你的 fiddle 的工作叉: http://jsfiddle.net/j3qrd3z7/3/