1

I am trying to read a simple CSV file which is "employee.csv":

Name, Age
Janik, 24
Jakob, 45
Anna, 30
Niklas, 35

The D3 script that I have to attempt this "employee.csv" file is as follows:

<!doctype html>
<html lang = "en">
    <head>
        <meta charset = "utf-8"/>
        <title>Loading CSV file in D3</title>
        <script src = "./d3/d3.min.js"></script>
    </head>

    <body>
        <script>
            d3.csv("./employee.csv", function(data)
                {
                    for(var i = 0; i < data.length; i++)
                    {
                        console.log(data[i]);
                        //console.log(data[i].Name);
                        //console.log(data[i].Age);
                    }

                });
        </script>
    </body>
</html>

This outputs each line from the CSV file. However, if I try to access each of the values from Age column, using the line

console.log(data[i].Age);

It gives the output undefined for each of the rows, whereas the the names are read fine

console.log(data[i].Name)

What am I doing wrong?

altocumulus
  • 21,179
  • 13
  • 61
  • 84
Arun
  • 2,222
  • 7
  • 43
  • 78
  • If you are using d3 v5, the d3.csv method is changed: https://stackoverflow.com/questions/49599691/how-to-load-data-from-a-csv-file-in-d3-v5 – smoore4 Dec 22 '18 at 16:09

1 Answers1

1

Your problem is the spaces in your csv file. Format it like this:

Name,Age
Janik,24
Jakob,45
Anna,30
Niklas,35

Here's a working Plunker that demonstrates the fix for your problem: http://plnkr.co/edit/XVo37T9WcKiLPIpIQHyv?p=preview

No spaces before commas in csv files. Now it works.

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
LaissezPasser
  • 396
  • 3
  • 18