【问题标题】:building html table using array containing csv data in javascript在javascript中使用包含csv数据的数组构建html表
【发布时间】:2019-03-25 01:10:13
【问题描述】:

我从 S3 对象获取 csv 数据并使用下面显示的代码将其转换为字符串,然后我将字符串转储到数组 arr 中,我认为我可以使用 <tr> 和 @987654322 构建一个 html 表@ 包含我从 csv 获得的数据的标签,当我在下面尝试时,我在 JavaScript 中没有得到理想的输出

let s3obj = new AWS.S3();
var arr = [];
var html = '<table>';
let s3param = {
      Bucket: 'test-bucket',
      Key: 'test-csv-file'
      };
      s3obj.getObject(s3param, function(err, data){
        if(err){
          throw err;
      } else {
         const body = Buffer.from(data.Body).toString('utf8'); //when i did console.log(typeof(body)) i get string datatype
         arr = body; //i tried converting string into array

    //below is the data i got back when i console.log(arr);

    //TEST,ROW,NUMBER,1
    //TEST,ROW,NUMBER,2
    //TEST,ROW,NUMBER,3

//below code tries to work on Array arr to get the output following it written into htmlTable variable

 for(var i=0; i < arr.length; i++)
    {
      htmlTable += '<tr>';
       for(var j = 0; j < arr[i].length; j++){
        htmlTable += '<td>';
        htmlTable += arr[i][j];
        htmlTable += '</td>';
        }
     htmlTable += '<tr>';
    }
//<table>
   // <tr><td>TEST</td><td>ROW</td><td>NUMBER</td><td>1</td></tr>
   // <tr><td>TEST</td><td>ROW</td><td>NUMBER</td><td>2</td></tr>   
   // <tr><td>TEST</td><td>ROW</td><td>NUMBER</td><td>3</td></tr>
   // <tr><td>TEST</td><td>ROW</td><td>NUMBER</td><td>4</td></tr>
//</table>

我得到的不是上面的输出。不知道我哪里出错了,我会很感激帮助构建 html 表格,就像上面一样。

【问题讨论】:

  • data.Body 最初返回时的格式是什么?
  • 当我输出data 参数时,我看到ContentType: "application/octet-stream
  • 我想知道数据体是什么格式,而不是数据的对象类型。
  • 对不起,我想找任何房产出去,但似乎找不到
  • 当你console.log(data.Body) 时会发生什么,这就是我要问的全部

标签: javascript aws-lambda aws-sdk


【解决方案1】:

根据body 的结构,您可以执行以下操作之一:

  1. 如果是带逗号的字符串数组:

    arr = body.map(line => line.split(","));
    
  2. 如果是带有换行符和逗号的单个字符串:

    arr = body.match(/.*/g).map(line => line.split(","));
    

【讨论】:

  • 谢谢@trincot,我得到带有换行符和逗号的单个字符串作为响应,Array arr 现在按预期打印值,感谢您的时间。
猜你喜欢
  • 2021-11-21
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多