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

时间:2018-01-18 16:21:19

标签: javascript jquery

我有一个包含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);

1 个答案:

答案 0 :(得分:0)

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

&#13;
&#13;
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);
&#13;
<script>
var csv = 'Club Name,Constituent ID,CnPh_1_01_Phone_number\r\nNorthwest\r\nTerritory,7930,example@noreply.com\r\nSouth Place,2343,johndoe@noreply.com\r\nNederlands,2334,nederlands@noreply.com';
</script>
&#13;
&#13;
&#13;