read csv in javascript

To read a CSV file in JavaScript, you can use the FileReader API to read the file and the split() method to parse the data into an array.

Here's an example code:

index.tsx
function handleFiles(files) {
  // Check for the various File API support.
  if (window.FileReader) {
    // FileReader are supported.
    getAsText(files[0]);
  } else {
    alert('FileReader are not supported in this browser.');
  }
}

function getAsText(fileToRead) {
  var reader = new FileReader();
  // Read file into memory as UTF-8.
  reader.readAsText(fileToRead);
  // Handle errors load.
  reader.onload = function(event) {
    var csv = event.target.result;
    processData(csv);
  };
  reader.onerror = function() {
    alert('Unable to read ' + fileToRead.fileName);
  };
}

function processData(csv) {
  var allTextLines = csv.split(/\r\n|\n/);
  var headers = allTextLines[0].split(',');
  var lines = [];

  for (var i = 1; i < allTextLines.length; i++) {
    var data = allTextLines[i].split(',');
    if (data.length == headers.length) {
      var line = {};
      for (var j = 0; j < headers.length; j++) {
        line[headers[j]] = data[j];
      }
      lines.push(line);
    }
  }
  // do something with the lines array
}
1046 chars
42 lines

In this code, the handleFiles() function is called when a file is selected. It checks if the FileReader API is supported by the browser and calls the getAsText() function to read the file.

The getAsText() function creates a FileReader object to read the file, and when the file is loaded, it calls the processData() function to parse the CSV data and store it into an array.

The processData() function splits the CSV data into an array of lines, and then further splits each line into an array of values using the , separator. Finally, it creates an object for each line with the header values as the keys and the data values as the values, and pushes these objects into an array.

You can then use the lines array to do whatever you need with the data.

gistlibby LogSnag