turtle
turtle

Reputation: 8073

Changing the underlying data associated with a D3 selection?

I have some circles in D3 with data attached to them:

var data = [[0,1],[2,10],[3,4],[2,4]]

var circles = svg.selectAll(".dot")
  .data(data)
  .enter().append("circle")
  .attr("class", "dot")
  .attr("r", 5)
  .attr("cx", d[0])
   .attr("cy", d[1])

I would like to modify the underlying data bound to these circles to be an array of objects:

circles = circles.data().map(function(d) {
  return {x: d[0], y: d[1]}
})

How can I change the underlying data associated with a D3 selection?

Upvotes: 2

Views: 553

Answers (1)

AmeliaBR
AmeliaBR

Reputation: 27544

You have two options: either modify the data array with the array.map function before joining it to your elements, or use the selection.datum method to modify each data object without changing the data join. You can't get the original data array back from your selection and modify it.

For the first option, your code would be:

var data = [[0,1],[2,10],[3,4],[2,4]];

data = data.map(function(d) {
  return {x: d[0], y: d[1]};
} );

var circles = svg.selectAll(".dot")
  .data(data)
  .enter().append("circle")
  .attr("class", "dot")
  .attr("r", 5)
  .attr("cx", function(d){return d.x;})
  .attr("cy", function(d){return d.y;})

For the second option, your code would be:

var data = [[0,1],[2,10],[3,4],[2,4]];

var circles = svg.selectAll(".dot")
  .data(data)
  .enter().append("circle")
  .datum( function(d) {
      return {x: d[0], y: d[1]};
  } )
  .attr("class", "dot")
  .attr("r", 5)
  .attr("cx", function(d){return d.x;})
  .attr("cy", function(d){return d.y;})

Upvotes: 1

Related Questions