Data structure returned by d3.csvParse

Viewed 53

In d3.js the csvParse function works like:

d3.csvParse("foo,bar\n1,2\n2,3"); 
// [{foo: "1", bar: "2"}, {foo: "2", bar:"3"}, columns: ["foo", "bar"]]

Q1: What the structure name of the returned data? especially the "columns" properties?

Outside d3.js, if I do

var data = [{foo: "1", bar: "2"}, {foo: "2", bar:"3"}, columns: ["foo", "bar"]]
//uncaught syntaxerror unexpected token ':'

Q2: Why is the error? How to get around?

2 Answers

The output you're seeing is just a regular JavaScript array and columns is simply a property of that array. In JavaScript, arrays can have properties.

If you have a look at the source code, you'll see this:

var rows = []

And then:

rows.columns = columns || [];

Here is a very basic example:

const arr = [1, 2, 3, 4, 5];
arr.columns = "foo";
console.log(arr)

Look at your browser's console (not the snippet one), you'll see this (in Chrome and Firefox, but not in Safari):

[1, 2, 3, 4, 5, columns: "foo"]

Regarding your error...

//uncaught syntaxerror unexpected token ':'

... have in mind that that is just the output in the console, that is not a valid array literal notation.

Q1: The columns: ["foo","bar"] makes an error. You can't assign the attribute columns if its not inside an object. What you can do instead is { columns: ["foo","bar"] }, which will crwate an object with the columns.

Related