json-to-csv-export icon indicating copy to clipboard operation
json-to-csv-export copied to clipboard

`headers` order isn't respected when `data` is an array of objects

Open nicogreenarry opened this issue 2 years ago • 0 comments

In the following case:

csvDownload({
  headers: ["first_column", "second_column"],
  data: [{ second_column: 2, first_column: 1 }],
  delimiter: ",",
});

...the output will actually be this, which is incorrect:

first_column,second_column
2,1

I haven't looked at the source code, but I imagine what's happening is that if data is an object, the library just serializes the object without regard for headers. But ideally it should read properties from each row object in the order of headers.

It's easy enough to fix in my own code, like this:

const headers = ["first_column", "second_column"]
const data = [{ second_column: 2, first_column: 1 }]
csvDownload({
  headers,
  data: data.map(row => headers.map(columnId => row[columnId])),
  delimiter: ",",
});

But ideally your library could do that so we don't have to :)

nicogreenarry avatar Nov 18 '23 01:11 nicogreenarry