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?
data() D3 is data driven. The data() function is used to join the specified array of data to the selected DOM elements and return the updated selection. D3 works with different types of data like Array, CSV, TSV, JSON, XML etc.
d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.
enter() function creates the initial join of the data with our DOM elements. Thus selecting only the elements that were not in the DOM yet. merge() function will select the DOM elements that did not exist in the DOM before and the ones that did. exit() function will select the DOM elements that are left from the join.
selectAll() function in D3. js is used to select all the element that matches the specified selector string. Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.
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__; });
If you want to access the entire data array from within a modification function, e.g., selection.attr
, you can use the fact that the entire selection is passed to the modification function as its third argument. So you can reconstruct the data array as follows:
mySelection.attr("stroke", (_, __, nodes) => { let data = d3.selectAll(nodes).data() // Now you can use data. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With