I'm using papaparse
to read csv file and then converting that file to array of objects. I'm using react-dropzone
to upload file and then then converting it into array of objects. But I need all of my headers to be in lower case, no blank space in between some columns to have data in form of array.
Here is my csv file
| Name | Age | Data one | Data two |
-------|-----|----------|----------|
| John | 23 | A, B | C |
-------|-----|----------|----------|
| Jane | 40 | E, F | G, H |
-------|-----|----------|----------|
Here is my code:
import React from "react";
import Dropzone from "react-dropzone";
import Papa from 'papaparse';
const App = () => {
const handleOnDrop = (acceptedFiles) => {
// acceptedFiles is the actual file uploaded by user
Papa.parse(acceptedFiles[0], {
header: true,
complete: (results) => {
console.log(results)
}
})
}
}
OutPut:
[
{
Name: "John",
Age: "23",
Data one: "A, B",
Data two: "C"
},
{
Name: "Jane",
Age: "40",
Data one: "E, F",
Data two: "G, H"
}
]
The output that I need is:
[
{
name: "John",
age: "23",
dataone: ["A", "B"], // Each individual data should be a string
datatwo: ["C"]
},
{
name: "Jane",
age: "40",
dataone: ["E", "F"],
datatwo: ["G", "H"]
}
]
I'm new to papaparse
and not sure how it's done
In the second parameter of parse
you can provide a function to the key transformHeader
to convert the column names. E.g. (headerName) => headerName.toLowerCase().replaceAll(' ', '')
.
The second problem is unrelated to papaparse. You can use results.map(result => { ...result, dataone: result.dataone.split(', ') })
and do the same for datatwo. Are the two column names known upfront or does it need to work dynamically and it needs to be applied to all strings with a comma?
Use the following code when the column names are in an array.
results.map(result => {
for(const column of columnsToconvertToArray) {
result[column] = result[column].split(', ');
}
return result;
});