In d3. The data() method takes three things:
- Function
- Array
- Nothing (when he acts as a recipient).
However, this is a problem:
In most situations, you can simply pass ["foo", "bar", "baz"] as data. So, if you have:
var data = ["foo", "bar", "baz"];
You can simply write:
.data(data)
However, in some situations, when an element inherits the data of the parent group, you must wrap it in an additional pair of brackets (check this last answer I wrote). We do this because the child gets its data as a function where the parent data is passed.
Check this:
var data = ["foo", "bar", "baz"]; var body = d3.select("body"); var divs = body.selectAll(".divs") .data(data) .enter() .append("div"); var par = divs.selectAll("p") .data(d => d) .enter() .append("p") .text(d => d);
<script src="https://d3js.org/d3.v4.min.js"></script>
Now the same code with an extra pair of brackets:
var data = ["foo", "bar", "baz"]; var body = d3.select("body"); var divs = body.selectAll(".divs") .data([data]) .enter() .append("div"); var par = divs.selectAll("p") .data(d => d) .enter() .append("p") .text(d => d);
<script src="https://d3js.org/d3.v4.min.js"></script>
In the first fragment 3 divs are created. For each of them, a string fact is passed in the paragraphs (d3 turns each line, for example, "foo" , into an array, such as ["f", "o", "o"] , and you get 3 paragraphs for each div).
In the second fragment, only one div is created (since the length of our array is 1), and the entire internal array ( ["foo", "bar", "baz"] ) is transferred to paragraphs.
source share