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

时间:2015-07-21 15:11:53

标签: javascript arrays object d3.js properties

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

例如,假设使用以下数组,我想返回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" },
    ]

UPDATE:这里,最后一行,我想引用red Delicious,但它返回Apple:undefined。这是一个jsfiddle来显示我遇到的问题(鼠标悬停时数据显示为“未定义”)。

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

1 个答案:

答案 0 :(得分:1)

当您创建转换后的数据集以传递到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']

小提琴的工作叉: http://jsfiddle.net/j3qrd3z7/3/