使用包含 javascript 中的 csv 数据的数组构建 html table
building html table using array containing csv data in javascript
我从 S3 对象获取 csv 数据并使用下面显示的代码将其转换为字符串,然后我将字符串转储到数组 arr 中,认为我可以构建一个 html table 使用 <tr>
和 <td>
标签,其中包括我从 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 table 就像上面一样。
根据 body
的结构,您可以执行以下操作之一:
如果是带逗号的字符串数组:
arr = body.map(line => line.split(","));
如果是带换行和逗号的单个字符串:
arr = body.match(/.*/g).map(line => line.split(","));
我从 S3 对象获取 csv 数据并使用下面显示的代码将其转换为字符串,然后我将字符串转储到数组 arr 中,认为我可以构建一个 html table 使用 <tr>
和 <td>
标签,其中包括我从 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 table 就像上面一样。
根据 body
的结构,您可以执行以下操作之一:
如果是带逗号的字符串数组:
arr = body.map(line => line.split(","));
如果是带换行和逗号的单个字符串:
arr = body.match(/.*/g).map(line => line.split(","));