user2829582
user2829582

Reputation: 245

How to create an array of nested objects from a csv file in D3.js?

This question uses the same data as one of my previous questions, but the question is different. I have a csv file that looks like this:

name,score,date
Bob,93,2014
Bob,85,2015
Barry,70,2015
...

No two people have the same name, but a person can have multiple entries. How can I create an array within the d3.csv callback function that looks like this?:

[{name: "Bob", values: [
   {score: 93, date: 2014},
   {score: 85, date: 2015}]}
 {name: "Barry", values: [
   {score: 70, date: 2015}]},
...

Normally I would be able to do this with plain javascript, but accessing property values with arrayName[objectIndex].objectPropertyName doesn't work within the d3 callback function.

Upvotes: 1

Views: 885

Answers (1)

somename
somename

Reputation: 998

d3.nest() function that will convert your csv data into key value pairs. Look at this plnkr link to view the objects in console. To get minimum maximum data see this updated plnkr.

d3.csv("data.csv", function(error, data) {
    console.log(data);
    var updated = d3.nest().key(function(d) {
        return d.name;
    }).sortKeys(d3.ascending).entries(data);
    console.log(updated);
})

Upvotes: 2

Related Questions