简体   繁体   中英

Is there any way to convert csv data to array of values

I have added jsfiddel link. 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:

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/

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 -

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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