Search code examples
javascripttypescript

JavaScript splitting a file content into key value pairs


I have the below UploadDocument event which has fileReader.result which logs below message to the console

Output in the Console

A,B
aa,dsf
adfa,dfsd
fdsafds,sdf

 uploadDocument(file) {
    let fileReader = new FileReader();
     fileReader.onload =(e) => {
      console.log(fileReader.result);
    }  
    fileReader.readAsText(this.file);

How can I split the above content (A,B...) in the console into a key value pairs ( Like a hashmap or Arraylist ) using javascript or Typescript?

I have tried splitting it var lines = fileReader.result.split(/[\r\n]+/g); console.log(lines);

Now how can I create A hashmap from this?


Solution

  • The reduce() array method can be used to build objects over each element, so we just need to split the file into multiple lines and then reduce the array of lines into an object.

    var map = fileReader.result.split('\n')
        .reduce((obj, line) => {
            var cols = line.split(',');
            // Tolerate empty lines. There may be one at the end of the input.
            if (cols.length >= 2) {
                obj[cols[0]] = cols[1];
            }
            return obj;
        }, {});
    

    Sample fiddle