4

I have a csv file in the following format

type,1,2,3,4,5,6,7,8,.... // Upto 48
type1,54.69801915,84.4717406,81.87766667,66.48516667,...
type2,51.57399106,84.23170179,82.13950136,67.37540461,...
......

I wanna draw a line chart using this csv data with d3. Once I nest them using below code

d3.nest().key(function(d) { 
    return d.type; 
  }).entries(data);

My json looks as follow

{ key: "type1", values: […] }

and inside values it is just a single element array and the value of that is { 1: 54.69801915, 2: 84.4717406, 3: 81.87766667, … }

But my expectation is that that would be a array something similar to

{ { 1: 54.69801915}, {2: 84.4717406}, {3: 81.87766667}, … }

Can someone tell me what I am doing wrong here? Or how should I get my expected format?

1 Answer 1

4

Well, that's the expected behaviour of d3.nest().

If you want that structure you shared in your question, with values as an array of objects, I suggest you write your own nesting function.

Here is an example of code that does what you want, using map and for...in. It's neither elegant nor beautiful, it's purposely verbose to be easily understood (I'm using only a few columns and rows in your data):

var csv = `type,1,2,3,4
type1,54.69801915,84.4717406,81.87766667,66.48516667
type2,51.57399106,84.23170179,82.13950136,67.37540461`;

var data = d3.csvParse(csv);

var nested = data.map(function(d) {
  var obj = {
    key: d.type,
    values: []
  };
  for (var prop in d) {
    if (prop !== "type") {
      obj.values.push({
        [prop]: d[prop]
      })
    }
  }
  return obj;
});

console.log(nested)
<script src="https://d3js.org/d3.v5.min.js"></script>

Some additional comments:

  • What yo have in your question is not a JSON, that's just a simple JavaScript object.
  • What you call an array at the end of your question is neither an array nor an object, that's actually invalid.
  • Finally, don't use numbers for your property names.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.