简体   繁体   English

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

[英]Is there any way to convert csv data to array of values

I have added jsfiddel link. 我添加了jsfiddel链接。 What I tried so far. 到目前为止我尝试过的。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks you 谢谢

 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 file data: CSV档案资料:

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

Result : 结果:

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

Expected: 预期:

\["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/ https://jsfiddle.net/eswar786/t5mpojr2/

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 loop take each value from the array and find out the wherever double quotes are occurring then replace that one with - 内部循环从数组中获取每个值,找出出现双引号的位置,然后将其替换为-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM