【问题标题】:Combine multiple CSV files into one 2D array将多个 CSV 文件合并为一个二维数组
【发布时间】:2020-11-12 15:02:32
【问题描述】:

我想使用 jquery 循环将多个 CSV 文件组合成一个二维数组。

    function drawChart(){
    
    filename="/projectUCF/SN00.csv";
    $.get(filename, function(csvString){
      var arrayData1 = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
      var removeRows = 1;
      while (removeRows--) {
        arrayData1.shift();
      }
      filename="/projectUCF/SN01.csv";
      $.get(filename, function(csvString){
      var arrayData2 = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
      var removeRows = 2;
      while (removeRows--) {
        arrayData2.shift();
      }
     
     var arrayData=[...arrayData1,...arrayData2];
     console.log(arrayData);

     var data = new google.visualization.arrayToDataTable(arrayData);
      
      var view = new google.visualization.DataView(data);
      view.setColumns([1,5]);
      
      
      var options = {
          title: "Battery State of Charge (7 days)",
          hAxis: {format: 'M/d hh:mm'},
          vAxis: {title: "Charge Level (in Percentage)", minValue:0, maxValue:100},
      legend: 'none'
      };
     chart.draw(view,options);  
     }); 
     });

     }

我想使用循环而不是多次使用 $.get。我是新手,所以任何帮助表示赞赏。

【问题讨论】:

    标签: javascript jquery csv jquery-csv


    【解决方案1】:

    一种方法是使用Promise.all。它接受一组承诺,并在所有承诺都解决后调用一个回调。因此,您可以像这样重组代码的检索/解析部分:

    var filenames = ["/projectUCF/SN00.csv", "/projectUCF/SN01.csv"];
    var promises = [];
    
    // create array of promises, one per file, that resolve after the file is retrieved a resolve with the parsed data
    filenames.forEach(function (filename) {
        promises.push(new Promise(function (resolve, reject) {
            $.get(filename, function (csvString) {
                var fileData = $.csv.toArrays(csvString, { onParseValue: $.csv.hooks.castToScalar });
                var removeRows = 1;
                while (removeRows--) {
                    fileData.shift();
                }
                resolve(fileData);
            });
        }));
    });
    
    // wait until all files have been retrieved, then continue
    Promise.all(promises).then(function (results) {
        var arrayData = [];
        results.forEach(function (fileData) {
            arrayData.push(...fileData);
        });
    
        // remaining code goes here
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-21
      • 2017-09-25
      • 2019-10-11
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多