有什么办法可以将CSV数据转换为值数组

时间:2019-05-06 09:54:18

标签: javascript typescript lodash

我添加了jsfiddel链接。到目前为止我尝试过的。任何帮助,将不胜感激。谢谢

function onFileSelect(input) {
  //this.itemHeaderName = itemHeaderName;
  var files = input.files;
  var csvData;
  if (files && files.length) {
    var fileToRead = files[0];
    var fileReader = new FileReader();
    fileReader.readAsText(fileToRead, 'UTF-8');
    fileReader.onloadend = function(x) {
      csvData = fileReader.result;
      onFileLoad(csvData);
    }

  }
}

function onFileLoad(fileLoadedEvent) {
  var csvSeparator = ',';
  var textFromFileLoaded = fileLoadedEvent;
  var csv = [];
  var rows = textFromFileLoaded.split('\n');

  _.forEach(rows, function(element) {
    var col = [];
    col = element.split(csvSeparator);
    csv.push(col);
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

<input id="uploadFile_hier" type="file" class="upload" onclick="onFileSelect(event.target)" multiple="false" />

CSV文件数据:

Part    Property    Level   Comments
Mercury Sub 2   TOP,Bottom,5678
copper  Material    1   KM
Iron    Thickness   4   NA,KA

结果:

\["part", "Property", "Level", "Comments"\]
\["Mercury", "Sub-Compound", "2", ""TOP", "NOZZLE", "BLOCK", "9100""\]
\["copper", "Material", "1", "KM"\]
\["Iron", "Thickness", "4", ""NA", "KA""\]

预期:

\["part", "Property", "Level", "Comments"\]
\["Mercury", "Sub-Compound", "2", "TOP,NOZZLE,BLOCK,9100"\]
\["copper", "Material", "1", "KM"\]
\["Iron", "Thickness", "4", "NA,KA"\]][1]

https://jsfiddle.net/eswar786/t5mpojr2/

1 个答案:

答案 0 :(得分:1)

rows.forEach(element => {
if (element.indexOf('"') >= 0) {
const str = element.slice(element.indexOf('"'), element.length);
const str1 = element.slice(0,element.indexOf('"'));
element = str1 + str.replace(/[',]+/g, '-');
} 

inside循环从数组中获取每个值,找出出现双引号的位置,然后将其替换为-

相关问题