1

I want to create a function in JavaScript that searches a CSV file using a someones name and then outputs the corresponding email address

CSV File Format:

 Name:               Email:
exampleName      example@example.com
exampleName2     example2@example.com
exampleName3     example3@example.com

I think I might be able to use PapaParse as the file will be stored online in a remote directory (not a local file).

Example Of PapaParse https://www.papaparse.com/

    // Parse CSV string
var data = Papa.parse(csv);

// Convert back to CSV
var csv = Papa.unparse(data);

// Parse local CSV file
Papa.parse(file, {
    complete: function(results) {
        console.log("Finished:", results.data);
    }
});

// Stream big file in worker thread
Papa.parse(bigFile, {
    worker: true,
    step: function(results) {
        console.log("Row:", results.data);
    }
});

If someone could help me create this function it would be much appreciated. Thank you in advanced.

L Heth
  • 13
  • 1
  • 6

1 Answers1

4

const csv = "Name,Email\nexampleName,example@example.com\nexampleName2,example2@example.com"
const csvData = Papa.parse(csv, {header:true}).data

function findEmailByName(name) {
  return csvData.filter(data => data.Name === name)[0].Email
}

console.log(
  findEmailByName('exampleName2')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.5.0/papaparse.min.js">
</script>
RustyDev
  • 1,094
  • 1
  • 9
  • 18