D3.js:获取附加到选择的数据的数组? [英] D3.js: Get an array of the data attached to a selection?
问题描述
的例子, http://bl.ocks.org/mbostock/3808218\">一般更新模式,然后尝试:
var text = svg.selectAll(text)
.data(data,function(d){return d;});
var textEnter = text.enter()。append(text)
.attr(class,enter)
.text return d;});
console.log('textEnter data',textEnter [0]);
var textEnterKeys = d3.map(textEnter [0],function(d){
return d .__ data__;
});
console.log('textEnterKeys',textEnterKeys);
但 textEnterKeys
看起来完全相同 textEnter
。
您可以简单地调用 .data()
在选择中没有任何参数以获取绑定数据。请参阅文档:
如果未指定值,则此方法将返回选择中第一个组的数据数组。返回数组的长度将匹配第一组的长度,返回数组中每个数据的索引将与选择中的相应索引匹配。如果选择中的某些元素为null,或者没有相关联的数据,则数组中的相应元素将是未定义的。
这对于 .enter()
选择不起作用,因为没有元素可以绑定数据。在这种情况下,可以使用 .map
函数:
.map(function(d){return d .__ data__;});
I'd like to get an array of all the data attached to a selection in D3.
I'm working with the example from the General Update pattern, and trying this:
var text = svg.selectAll("text")
.data(data, function(d) { return d; });
var textEnter = text.enter().append("text")
.attr("class", "enter")
.text(function(d) { return d; });
console.log('textEnter data', textEnter[0]);
var textEnterKeys = d3.map(textEnter[0], function(d) {
return d.__data__;
});
console.log('textEnterKeys', textEnterKeys);
But textEnterKeys
just looks exactly the same as textEnter
. How can I get an array of the data attached to each element in the selection?
You can simply call .data()
without any arguments on a selection to get the bound data. See the documentation:
If values is not specified, then this method returns the array of data for the first group in the selection. The length of the returned array will match the length of the first group, and the index of each datum in the returned array will match the corresponding index in the selection. If some of the elements in the selection are null, or if they have no associated data, then the corresponding element in the array will be undefined.
This does not work for the .enter()
selection as there are no elements yet to which the data can be bound. In this case, the .map
function can be used:
textEnter.map(function(d) { return d.__data__; });
这篇关于D3.js:获取附加到选择的数据的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!