const fs = require('fs');
fs.readFile('./data.csv', (err, data) => {
if (err) {
throw new Error(err);
}
const csv = String(data) // convert the buffer to a string
.split('\n') // Split the string into an array where each item contains one line
.filter(Boolean); // Remove any empty lines
// Do the rest of the operations on the CSV data here
});
1条答案
按热度按时间gg58donl1#
第一步是分离数据和列标题。我将假设csv在程序中存储为一个字符串数组,每个字符串代表一行,即
如果您的CSV还没有以这种方式表示,您可以使用
fs
模块来实现:在这种情况下,我们可以使用spread运算符轻松地将它们拆分,然后在逗号上拆分每个字符串:
现在我们的对象看起来像这样:
现在我们可以继续将数据数组中的每个数组Map到一个对象,使用每个值的索引将其Map到CSV中的特定标题。
当然,我们必须将这个Map的数据对象返回到某个地方,或者将它赋给一个新的变量,因为
Array.map()
函数不会更新原始数组,而是创建一个新数组。将所有这些放在一个代码片段中,看起来如下: