0

I have a CSV file and I need to display in the terminal only the second column. I'm using javascript and nodejs. My CSV file is in a local folder. My CSV data look like this:

name,emails,name1,email1,name2,email2,name3,email3,name4,email4,name5,email5

It's like an array with two columns and six rows, first one with name and second one with emails. I only want to return the list of emails without the heading in the terminal. Later I'll have to use this email list to compare it with an other array.

I think it is possible with papaparse but I don't understand how to use it. I also know that fs module can be use to read the entire file.

If it's possible to convert the data in an array with or without keys/values like this it will also be perfect:

[ name:'name1', email:'email1', name:'name2', email:'email2', name:'name3', email:'email3', name:'name4', email:'email4', name:'name5', email:'email5' ]

Knowing that I also have to do it with an other CSV file that contain 9 columns and 960 rows.

1 Answer 1

1

This code should parse a CSV file in the format you mention, e.g.

test.csv

name,emails
name1,email1
name2,email2
name3,email3
name4,email4
name5,email5

app.js

const Papa = require('papaparse');
const fs = require("fs");

let csvData = fs.readFileSync("test.csv", "utf-8");
csvData = csvData.trim().replace(/([^,]+),\s*([^,]+),\s*/gi, '$1,$2\n');
console.log("Adjusted csv:", csvData);

let { meta, data } = Papa.parse(csvData, { header: true });

console.log("Parsed data:", data);
console.log("Metadata:", meta);

The parsed data would look like so:

[
  { name: 'name1', emails: 'email1' },
  { name: 'name2', emails: 'email2' },
  { name: 'name3', emails: 'email3' },
  { name: 'name4', emails: 'email4' },
  { name: 'name5', emails: 'email5' }
]
Sign up to request clarification or add additional context in comments.

10 Comments

Not exactly but I think it's because my CSV is strange, it give me something like this:
Yes it look exactly like this
I've updated the code to split the data into rows so PapaParse can process it.
Sorry my bad, i didn't see the other console.log
Thank you very much it's exactly what I wanted
|

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.