0

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

1 Answer 1

2

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Column names that have to be converted into the array are known. Eg: columnsToconvertToArray = ["dataone", "datatwo"]. SO I want to use columnsToconvertToArray in papaparse to convert cells into array for those columns itself. @Michiel
@iCodeByte I extended my answer. Does it do what you want?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.