如果变量匹配csv中的字符串,则将其旁边的字符串存储到变量中

问题描述 投票:0回答:1

我有一个3列的csv文件。如果同一行中标题成分ID下的字符串与变量clubID匹配,我想将CnPh_1_01_Phone_number标题下的字符串存储到变量clubEmail中。

        var clubID = 2343
        $.ajax({
            type: "GET",
            url: "http://www.filehosting.org/file/details/719843/testing.csv",
            dataType: "text",
            success: function(data) {processData(data);}
         });
    });

    function processData(allText) {
        var allTextLines = allText.split(/\r\n|\n/);
        var headers = allTextLines[0].split(',');
        var lines = [];

        for (var i=1; i<allTextLines.length; i++) {
            var data = allTextLines[i].split(',');
            if (data.length == headers.length) {

                var tarr = [];
                for (var j=0; j<headers.length; j++) {
                    tarr.push(headers[j]+":"+data[j]);
                }
                lines.push(tarr);
            }
        }
        // alert(lines);
    console.log(lines);
javascript jquery
1个回答
0
投票

注意:我用csv文件中的字符串替换了ajax,以便在代码段中使用:

String.prototype.processCSV = function(matchValue, matchColName, outColName) {
  let allTextLines = this.split(/\r\n|\n/);

  let matchIndex = allTextLines[0].split(',').indexOf(matchColName);
  let outIndex = allTextLines[0].split(',').indexOf(outColName);
  
  if (matchIndex < 0 || outIndex < 0) 
    return '';
    
  allTextLines.shift();
  
  let matchedRow = allTextLines.map(item => item.split(',')).find(cols => {
    return cols.length > matchIndex && cols.length > outIndex && cols[matchIndex] == matchValue; 
  });
  
  return (matchedRow ? matchedRow[outIndex] : '')
}

var clubMail = csv.processCSV(2343, 'Constituent ID', 'CnPh_1_01_Phone_number');
console.log(clubMail);
<script>
var csv = 'Club Name,Constituent ID,CnPh_1_01_Phone_number\r\nNorthwest\r\nTerritory,7930,[email protected]\r\nSouth Place,2343,[email protected]\r\nNederlands,2334,[email protected]';
</script>
© www.soinside.com 2019 - 2024. All rights reserved.