javascript - 将对象属性传递给 D3 'enter()'

标签 javascript d3.js

我有一个具有许多属性的对象,我尝试通过将特定属性传递给下面的 barChart 函数来创建条形图。但是当它到达 attr 时,properyItem未定义。不知道该怎么做。如果我对属性名称进行硬编码,它就可以工作(例如:d.MURDER)。

var barChart = function(propertyItem) {
    if (propertyItem == null) {
        propertyItem = "ROBBERY";
    }
    var svg = d3.select("body").append("svg");
    svg.attr("width", w).attr("height", h);
    svg.selectAll("rect")
        .data(dataset)
        .enter()
        .append("rect")
        .attr("x", function(d, i) {
            return i * (w / dataset.length);
        })
        .attr("height", function(d) {
            return d.propertyItem * 4;
        })
        .attr("width", w / dataset.length - barPadding)
        .attr("y", function(d) {
            return h - d.propertyItem * 4;
        })
}

最佳答案

假设您的 propertyItem 确实存在于 dataset 中,解决方案很简单:使用 bracket notation 。例如:

.attr("height", function(d) {
    return d[propertyItem] * 4;
});

原因是函数内的 propertyItem 只是一个字符串。如果你这样做...

d.propertyItem

...浏览器不会查找字符串的相同属性,而是查找字面上名为 propertyItem 的属性。让我们展示一下:

var obj = {
  foo: "this is what I want!",
  propertyItem: "this is not what I want..."
};
var propertyItem = "foo";
console.log("obj.propertyItem returns: " + obj.propertyItem)
console.log("obj[propertyItem] returns: " + obj[propertyItem])

因此,我认为您的 dataset 数组中没有字面上名为 propertyItem 的属性,它返回 undefined

这是一个包含一些虚拟数据和代码的演示,但使用括号表示法:

var dataset = [{
  foo: 80,
  bar: 10
}, {
  foo: 30,
  bar: 12
}, {
  foo: 70,
  bar: 11
}, {
  foo: 42,
  bar: 17
}];
var w = 400,
  h = 200,
  barPadding = 10;
var barChart = function(propertyItem) {
  if (propertyItem == null) {
    propertyItem = "ROBBERY";
  }
  var svg = d3.select("body").append("svg");
  svg.attr("width", w).attr("height", h);
  svg.selectAll("rect")
    .data(dataset)
    .enter()
    .append("rect")
    .attr("x", function(d, i) {
      return i * (w / dataset.length);
    })
    .attr("height", function(d) {
      return d[propertyItem] * 4;
    })
    .attr("width", w / dataset.length - barPadding)
    .attr("y", function(d) {
      return h - d[propertyItem] * 4;
    })
}
barChart("foo")
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

关于javascript - 将对象属性传递给 D3 'enter()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47949237/

相关文章:

javascript - d3 饼图/ donut chart 中标签的过渡

javascript - 您的连接不是 Node js 中的私有(private)错误

javascript - 从任意 JavaScript 对象中单态检索一些元信息 (v8)?

javascript - NodeJS/ExpressJS : Serving single concatenated JS file in production

javascript - 添加 Javascript Onclick 到 .css 文件

javascript - 使用 angular/d3/css3/(?) 通过动画树状图创建体验

d3.js - d3.js 图表的工具提示问题

javascript - 将鼠标事件分配给 svg :text in d3. js

javascript - d3JS : Drawing Line Segments from CSV

javascript - 如何在 javascript 幻灯片加载之前停止加载图像?