将Papaparse行转换为对象

时间:2017-04-29 04:14:32

标签: javascript node.js csv papaparse

papaparse支持是否返回由标题列键入的对象实例数组?

例如,我有一个像这样的CSV文件:

sku, location, quantity
'sku1', 'Chicago', 3
'sku2', 'New York, 4

我希望papaparse返回的数组看起来像这样:

 [{sku: 'sku1', location: 'Chicago', quantity: 3}, ...]

这也应该是可能的:

results[0].sku == 'sku1'
results[1].quantity == 4

2 个答案:

答案 0 :(得分:2)

尝试将structure(list(Taxa = c("Cyano", "Cyano", "Cyano", "Cyano", "Dolicho", "Dolicho", "Dolicho", "Dolicho", "Gompho", "Gompho", "Gompho", "Gompho", "Nosto", "Nosto", "Nosto", "Nosto"), Treatment = c("Control", "D. pulex", "D. magna", "0.25", "Control", "D. pulex", "D. magna", "0.25", "Control", "D. pulex", "D. magna", "0.25", "Control", "D. pulex", "D. magna", "0.25"), Growth = -10:5, star = c("", "Y", "Y", "", "", "Y", "Y", "Y", "", "", "", "Y", "", "", "", "Y")), class = "data.frame", row.names = c(NA, -16L)) 添加到config参数。

来自the docs

标题:如果为true,则已解析数据的第一行将解释为字段名称。字段名称数组将以meta返回,并且每一行数据都是一个由字段名称作为键值的对象,而不是简单的数组。与标题行的字段数不同的行将产生错误。警告:重复的字段名称将覆盖以前具有相同名称的字段中的值。

例如:

header: true

鉴于您的数据应该产生

Papa.parse('./data.csv', {
  download: true,
  header: true, // gives us an array of objects
  dynamicTyping: true,
  complete: ({ data }) => console.log(data),
});

答案 1 :(得分:0)

可以通过简单的javascript working example:

中的几行来实现

我的csv文件数据:

sku, location, quantity

'sku1', 'Chicago', 3

'sku2', 'New Yoark, 4