Modifying Underlying Data

by Nivaldo

HTML

<p>Q: I have some circles in D3 with data attached to them. I would like to modify the underlying data bound to these circles to be an array of objects.</p>
<p>A: 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.</p>

JavaScript

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

var svg = d3.select("body").append("svg").append("g").attr("transform","translate(20,20)");

/*
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;})
*/

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;})