2

I am importing data from a csv file that contains headers with spaces in the middle of some of the fields.

For example the following has a column named 'Date Purchased';

Value,Date Purchased,Score
12345,2011-03-23,99
22345,2011-03-24,100
32345,2011-03-25,99
42345,2011-03-26,100

I know that RFC 4180 specifies that this is normal;

Within the header and each record, there may be one or more fields, separated by commas. Each line should contain the same number of fields throughout the file. Spaces are considered part of a field and should not be ignored.

But when I then go to import the data using the d3.csv function, I need to reference the 'Data Purchased' column in a way that makes allowances for the space. The following piece of script would be the most basic solution, but JavaScript is not allowing the use of the space within the variable name (I know it seems obvious, but I'm trying to spell this out logically)

d3.csv("sample-data.csv", function(error, data) {
    data.forEach(function(d) {
        d.date = parseDate(d.Date Purchased);
    });

console.log(data) shows that the file is being imported without problem and that the data in the 'Data Purchased' column is called 'Data Purchased'.

I have found references that suggest the inclusion of a decimal point, an underscore or a hyphen instead of a space (d.Date.Purchased, d.Date_Purchased, d.Date-Purchased), but that doesn't seem to work either.

I could write a simple php parser to remove the spaces, but it feels like there is a simple solution that that will work in JavaScript / d3 and I'm just missing it.

1 Answer 1

10

Here's how

d.date = parseDate(d['Date Purchased']);
1
  • Ahh... Perfecto! Many thanks! (I initially mistyped your solution, but got there eventually :-))
    – d3noob
    Feb 11, 2014 at 23:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.