首页 > 解决方案 > 使用 Javascript 和节点 csv-parse 将 csv 文件解析为数组

问题描述

我有一个项目,我必须处理输入 CSV 文件并将其存储到可以添加的数组中,然后将其打印到 CSV 文件中。然后,我将事务数据用于我的项目的其余部分,因此能够完成这部分至关重要,因为将使用其他 CSV 文件执行测试。

我的问题是,在使用 csv-parse 时,如果我使用 console.table(results); 当我在命令终端中运行 .js 文件时,它会显示 csv 对象,因此我知道它的解析,但无论我做什么,我都无法让对象进入我的数组变量。

控制台.table(结果);

请有人给我一个关于我哪里出错的提示:

var fs = require('fs');
var parse = require('csv-parse');


var transactionValues = []; //Need an array to hold transactions

//constuctor for transactions
function addData (id, accountType, initiatorType, dateTime, transactions) {
  var data = {
    "AccountID" : id,
    "AccountType" : accountType,
    "InitiatorType" : initiatorType,
    "DateTime" : dateTime,
    "TransactionValues" : transactions
  }
  transactionValues.push(data); //should add a new line
}

    var parser = parse({columns: true}, function (err, results) {
console.table(results);
addData(results.index[0].AccountID, results.index[0].AccountType, results.index[0].InitiatorType, results.index[0].DateTime, results.index[0].TransactionValue, 0);
}); //attempted to save the objects into the array but no success

fs.createReadStream(__dirname+'/testData/customer-1234567-ledger.csv').pipe(parser)

console.log(transactionValues); // array is empty

标签: javascriptarrayscsv

解决方案


我相信results它已经是一个正常的数组,因为它是从 csv-parse 返回的。您正在尝试使用 访问第一个元素results.index[0],但它只是results[0]. 另一个问题是fs.createReadStream(...).pipe(...)异步的。这意味着您console.log将在解析完成之前运行。您需要将解析后必须运行的任何代码放入parse函数的回调中。像这样的东西:

var parser = parse({columns: true}, function (err, results) {
  console.table(results);
  for (const row of results) { //loop through each object parsed from the csv
    addData(row.AccountID, row.AccountType, row.InitiatorType, row.DateTime, row.TransactionValue, 0);
  }
  console.log(transactionValues); // this should be populated properly

  /* Do anything that needs to use transactionValues here */
});

推荐阅读