mbostock/d3 — Issue #470: Reading data from selections?
Author: shawnbot
Created: 2012-01-25 23:08:34+00:00
State: open

I've been trying to figure out how to easily pull data from the DOM with D3, to no avail. ES5's `Array.prototype.map()` and [jQuery.map()](http://api.jquery.com/map/) both return new lists of data by passing each element through a transformation function, but d3's `selection.map()` doesn't. This means that in order to extract data from the DOM, e.g. to turn this:

```html

name	age

Jack	30

Jane	31

```

into this:

```javascript
[
{name: "Jack", age: "30"},
{name: "Jane", age: "31"}
]
```

You have to do things like this:

```javascript
var data = [];
d3.select("table")
.selectAll("tbody tr")
.each(function() {
var person = {};
person.name = d3.select("td:first-child").text();
person.age = d3.select("td:nth-child(2)").text();
data.push(row);
});
```

But what would be really sweet is this:

```javascript
var table = d3.select("table"),
// ["name", "age"]
columns = table.selectAll("thead th").map(function() {
return d3.select(this).text();
}),
rows = table.selectAll("tbody tr")
.map(function() {
var row = {};
d3.select(this).selectAll("td").each(function(d, i) {
person[columns[i]] = d3.select(this).text();
});
});
```

So, two things:

1. I think `selection` objects need a function for returning lists of data, so that if you're extracting data from the DOM you can do things like derive min and max values, create scales, etc. without jumping through hoops like the `data.push()` example above.
2. I think that function should be called `map()`, and that the current functionality of `map()` should be integrated into `data()`.

I can already do this easily with jQuery, or even just with regular old DOM JavaScript. But it would be great not to have to use both jQuery and d3 in order to extract data from the DOM and visualize it in another form with d3.

Discuss!