I Like
I Like

Reputation: 1847

d3js: how to bind data within a single object

I'm trying to create a bar chart using a single object. I isolated this object from the larger dataset, but now am having trouble using .data on it. It seems the only format in which .bind will work would be several objects within an array. My project is made so that when a user clicks on a certain date, it grabs the object from the dataset and creates the corresponding bar graph. Would bind work in this context?

Object {Date: "2010", Paper and Paperboard: "71310", Glass: "11520", Ferrous: "16920", Aluminum: "3510"}

Upvotes: 1

Views: 534

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

In D3, the data() function accepts three things:

  1. An array
  2. A function
  3. Nothing

That being said, if you have just a single object, you have to wrap it in an array:

var myData = [{Date: "2010", Paper and Paperboard: "71310", Glass: "11520", Ferrous: "16920", Aluminum: "3510"}];

And then:

data(myData)

Or, alternatively:

var myObject = {Date: "2010", Paper and Paperboard: "71310", Glass: "11520", Ferrous: "16920", Aluminum: "3510"};

data([myObject])

But you'll have only one element in your enter selection.

A better approach would be iterating over that object to create an array of objects.

PS: We all know that in JavaScript arrays are objects, but I believe my point here is clear: the data() function accepts an specific type of object, which we call an array.

Upvotes: 1

Related Questions