gpt4 book ai didi

javascript - 遍历 csv

转载 作者:行者123 更新时间:2023-12-03 02:13:44 24 4
gpt4 key购买 nike

我正在尝试解析 csv:

col1,col2,col3
a,b,1
d,e,2

当我运行以下代码时

var fs = require("fs");
var d3 = require("d3");

fs.readFile("test.csv", "utf8", function(error, data) {
var data = JSON.stringify(d3.csvParse(data));
data.map((item, i) => console.log(`Hello ${item.col1} this ${item.col2} there are ${item.col3} blabla`));
});

我收到 TypeError: data.map is not a function

虽然以下运行正常。

var data = [{ "col1":"a","col2":"b","col3":1},
{ "col1":"d","col2":"e","col3":2}]

data.map((item, i) => console.log(`Hello ${item.col1} this ${item.col2} there are ${item.col3} blabla`));

最佳答案

d3.csvParse 返回一个数组,但您可以在此处将其转换为字符串:

var data = JSON.stringify(d3.csvParse(data));

当然,字符串没有.map。您可能想迭代数组:

const newData = d3.csvParse(data);
newData.forEach((item, i) => console.log(`Hello ${item.col1} this ${item.col2} there are ${item.col3} blabla`));

(不要使用 .map 因为您没有将其转换为新数组,至少在您发布的代码中没有)

关于javascript - 遍历 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49444205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com