javascript - 如何从绑定(bind)到 d3.js 元素的数组对象中仅返回唯一值

标签 javascript jquery d3.js

我对 d3.js 非常陌生。我有父 g 容器,看起来像这样

var g = pieParentG.append("g")
    .attr("transform", "translate(" + xVal + "," + yVal + ")")
    .selectAll("arc")
    .data(pie(dataVal))
    .enter()
    .append("g")
    .attr("class", "arc");

我正在尝试添加一个子文本节点,如下所示

 var textG = g.append("g")
     .append("text")
     .html(function(d) {
         return d.data.zone;
     });

但是,对象的 dataval 数组可能包含重复值。数组的示例是

[{
        "count": 1267,
        "path": 1,
        "zone": "Bandra-Pillers"
    },
    {
        "count": 697,
        "path": 2,
        "zone": "Bandra-Pillers"
    },
    {
        "count": 560,
        "path": 3,
        "zone": "Bandra-Pillers"
    }
]

文本字段应映射到数组中的此区域字段。如果出现重复值,例如在本例中,我只想附加 1 个文本元素。 Array.filter 函数是一个选项吗?如果是,那么我在哪里使用它?

最佳答案

the text field should map to this zone field in the array. In case of duplicate values, such as in this case, I want only 1 text element to be appended. Is the Array.filter function an option? If yes, then where do I use it?

实际上,如果您只想从数组中返回 1 个与此 zone 匹配的对象,则不能使用 .filetr(),因为它将返回该区域的所有元素具有相同的区域

您可以使用Array#find() 它将仅返回第一个通过条件的对象:

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

这就是您的代码:

var myObj = dataVal.find(function(item) {
  return item.zone === "Bandra-Pillers";
});

演示:

var dataVal = [{
    "count": 1267,
    "path": 1,
    "zone": "Bandra-Pillers"
  },
  {
    "count": 697,
    "path": 2,
    "zone": "Bandra-Pillers"
  },
  {
    "count": 560,
    "path": 3,
    "zone": "Bandra-Pillers"
  }
];

var myObj = dataVal.find(function(item) {
  return item.zone === "Bandra-Pillers";
});

console.log(myObj);

编辑:

你可以在.html()的回调函数中调用它,如下所示:

var textG = g.append("g")
     .append("text")
     .html(function(d) {
         return dataVal.filter(function(item){
              return item.zone === zone; //Pass zone variable here
         })[0].data.zone;
});

关于javascript - 如何从绑定(bind)到 d3.js 元素的数组对象中仅返回唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47814094/

相关文章:

javascript - 使用 JavaScript 触发 CSS 动画

javascript - d3.js 使用相同的选择选项控制两个图形

JavaScript 增量 y=++x

javascript - window.open(url) 取代前一个 window.open(url) 的窗口

javascript - jQuery 幻灯片无法正常工作,显示 :none;

javascript - 类似于 Medium.com 的页面过渡动画

javascript - 为什么 Flexigird 不能在 IE 上运行

javascript - 使用 jQuery 将事件绑定(bind)到表格单元格

javascript - 使用 D3.js 的响应式词云

javascript - D3.js 链式过渡,用于不同形状的复合动画