Search code examples
javascriptnode.jspapaparse

How to search a CSV file using a key in JavaScript


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      [email protected]
exampleName2     [email protected]
exampleName3     [email protected]

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.


Solution

  • const csv = "Name,Email\nexampleName,[email protected]\nexampleName2,[email protected]"
    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>