0

say if I have csv file with :

Heading 1 , Heading 2 , Heading 3

Value 1 , Value2 , Value 3

All I want is to create a map that stores Heading 1 as a key and Heading 2 as value;

like map.set(value1 , value2)

How do I do this while I read the file in javascript ?

function processData(allText) {
    var allTextLines = allText.split("\r");

    for (var i=1; i<allTextLines.length; i++) {
        var data = allTextLines[i].split(',');
        console.log(data[0]);
        map1.set(data[0] , data[1]);
        }
    }

so far I tried to do this . But it doesn't work. It doesn't read the file at all. Any help is appreciated. Thanks

Bahij.Mik
  • 1,358
  • 2
  • 9
  • 22
pal
  • 23
  • 6

1 Answers1

1

If you have a series of items separated by commas (,), the you can iterate the String and explode or split the items. This can be done with Vanilla JavaScript. The magic part is the for() loop; iterating it by 2 instead of by 1, which is most commonly seen.

$(function() {
  var myString = "Header 1,Value 1,Header 2,Value 2,Header 3,Value 3";

  var parts = myString.split(",");

  var myData = {};
  for (var i = 0; i < parts.length; i += 2) {
    myData[parts[i]] = parts[i + 1];
  }
  
  console.log(myData);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If your file has multiple lines, and the first line is Headers, for example:

Header 1,Header 2,Header 3
Value 1,Value 2,Value 3
Value 4,Value 5,Value 6

You'll have to treat it differently. When it's brought into JS, it will be one big String, and you will have to first split it by End Of Line (EOL). This will create an Array of Strings that must be iterated. You will want to make an Array of Keys and then a Matrix of Values.

Since the file is Local, you will need to first get the File from the User. This is discussed here: How to read data From *.CSV file using javascript? and here: Reading in a local csv file in javascript? You will have to determine the best method for yourself.

One way is to use a File Input. There are drawbacks and caveats due to security and browsers, but it might work.

$(function() {
  var fileInput = $("#getFile");

  function toObj(keys, vals) {
    var obj = {};
    for (var i = 0; i < keys.length; i++) {
      obj[keys[i]] = vals[i];
    }
    return obj;
  }

  function stringToObject(str, header) {
    if (header == undefined) {
      header = false;
    }
    var lines = str.split("\n");
    var k = [],
      m = [];
    if (header) {
      k = lines.splice(0, 1);
      k = k[0].split(",");
    }
    $.each(lines, function(i, el) {
      if (el.length) {
        m.push(el.split(","));
      }
    });
    if (k.length) {
      var r = [];
      $.each(m, function(i, el) {
        r.push(toObj(k, el));
      });
      return r;
    } else {
      return m;
    }
  }

  function readFile() {
    var reader = new FileReader();
    reader.onload = function() {
      var newData = stringToObject(reader.result, $("#header").prop("checked"));
      console.log(newData);
      $("#out").html("<pre>" + reader.result + "</pre>");
    };
    reader.readAsBinaryString(fileInput[0].files[0]);
  };

  fileInput.change(readFile);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="file input">
  <input type="checkbox" id="header" checked="checked"> <label>CSV Header</label><br />
  <input type="file" id="getFile" />
</div>
<div id="out"></div>
Twisty
  • 30,304
  • 2
  • 26
  • 45
  • How do I read from the file. I understand the looping stuff. I am not able to open the file and read from there – pal Apr 14 '20 at 23:31
  • @pal where is the file located? On a Server? Locally? – Twisty Apr 14 '20 at 23:32
  • It is located locally – pal Apr 14 '20 at 23:32
  • @pal updated answer, and this might help you: https://stackoverflow.com/questions/7431268/how-to-read-data-from-csv-file-using-javascript Looks like you didn't search very long before posting, I found this on my first look. – Twisty Apr 14 '20 at 23:38
  • Thank you for your time. I did search and found the exact solution . When I try to input thr url link for csv file in my case it doesn't read also may I know what $(document) mean in the code ? – pal Apr 14 '20 at 23:45
  • @pal updated my answer again. Not sure what you are asking about `$(document)`. – Twisty Apr 15 '20 at 00:39