Binding data to DOM elements
Data binding techniques are very powerful in D3.js because they enable us to generate graphical content based on data. In general, with the data-driven approach, we can declare the graphical elements to match the data instead of looping through the data and drawing the elements one by one.
selection.data(values[, key])
D3-Selections provide the .data([values[, key]])
method to bind an array of arbitrary data to a Selection. It will return a new Selection that stores the bound data internally and binds every element of the data array to an element of the Selection.
The first values
argument is an array of values or a function that returns an array of values. With the second optional key
argument, we can specify a function that identifies each element of the array. The key
argument is important for D3.js to identify and keep track of the elements for the data joins. Let's first take a look at a simple example:
<svg width="400" height="200"...