D3.js - Nested Data Works But Selection Does NOT Follow

d3.js

47 观看

1回复

315 作者的声誉

trying to understand how to deal with nested Data in D3 I came up with this example:

<script>

data = [
{ Name: "jim", color: "blue", Points: [{x:0, y:5 }, {x:25, y:7 }, {x:50, y:13}] },
{ Name: "bob", color: "green", Points: [{x:0, y:10}, {x:27, y:30}, {x:57, y:60}] }
];

var print = function(d){d3.select("body li")
    .selectAll("b")
    .data(d)
    .enter()
        .append("b")
        .text(function(i){return ' - ' + i.x;});}

d3.select("body")
    .selectAll("li")
    .data(data)
    .enter()
        .append("li")
        .text(function(d){print(d.Points);});

</script>

I would have expected this to produce this:

<li>
  <b> - 0</b>
  <b> - 25</b>
  <b> - 50</b>
</li>
<li>
  <b> - 0</b>
  <b> - 27</b>
  <b> - 57</b>
</li>

instead it produces the following:

<li>
  <b> - 0</b>
  <b> - 27</b>
  <b> - 57</b>
</li>
<li></li>

I understand that when I select "body li" I select the two existing "li" and I am giving only one "d" data that goes only in the first "li", but I really do not understand how D3 works in this case and how to iterate through the "li".

作者: user3755529 的来源 发布者: 2017 年 12 月 27 日

回应 1


2

1827 作者的声誉

决定

I'd create the li first, then use the bound data to create the bullets:

data = [
{ Name: "jim", color: "blue", Points: [{x:0, y:5 }, {x:25, y:7 }, {x:50, y:13}] },
{ Name: "bob", color: "green", Points: [{x:0, y:10}, {x:27, y:30}, {x:57, y:60}] }
];
//original selection creates two 'li' objects
var lines = d3.select("body")
    .selectAll("li")
    .data(data)
    .enter()
        .append("li");

//using the same selection; we can iterate (function(d,i) where i is the index) over each 'li' object
//to do so, we create a new selection where the data is pulled from the data in the 'lines' variable
var bullets = lines.selectAll('b')
    .data(function(d) { return d.Points; }) //returns the Points variable from the data already bound to the variable 'lines'
  .enter()
  .append('b')
  .text(function(d,i) {return ' - ' + d.x; }); //iterates (i) over each lines object and return the x variable from the bound data.
作者: Ryan Morton 发布者: 2017 年 12 月 27 日
32x32