No need to write your own...
(不需要自己写...)
The jQuery-CSV library has a function called $.csv.toObjects(csv)
that does the mapping automatically.
(jQuery-CSV库具有一个称为$.csv.toObjects(csv)
的函数,该函数会自动执行映射。)
Note: The library is designed to handle any CSV data that is RFC 4180 compliant, including all of the nasty edge cases that most 'simple' solutions overlook.
(注意:该库旨在处理符合RFC 4180的所有CSV数据,包括大多数“简单”解决方案都忽略的所有讨厌的边缘情况。)
Like @Blazemonger already stated, first you need to add line breaks to make the data valid CSV.
(就像@Blazemonger已经说过的一样,首先您需要添加换行符以使数据有效为CSV。)
Using the following dataset:
(使用以下数据集:)
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2
Use the code:
(使用代码:)
var data = $.csv.toObjects(csv):
The output saved in 'data' will be:
(保存在“数据”中的输出将是:)
[
{ heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1" }
{ heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" }
]
Note: Technically, the way you wrote the key-value mapping is invalid JavaScript.
(注意:从技术上讲,您编写键值映射的方式是无效的JavaScript。)
The objects containing the key-value pairs should be wrapped in brackets.(包含键值对的对象应放在方括号中。)
If you want to try it out for yourself, I suggest you take a look at the Basic Usage Demonstration under the 'toObjects()' tab.
(如果您想自己尝试一下,建议您看一下“ toObjects()”选项卡下的“ 基本用法”演示 。)
Disclaimer: I'm the original author of jQuery-CSV.
(免责声明:我是jQuery-CSV的原始作者。)
Update:
(更新:)
Edited to use the dataset that the op provided and included a link to the demo where the data can be tested for validity.
(编辑以使用op提供的数据集,并包括指向演示的链接,在演示中可以测试数据的有效性。)
Update2:
(更新2:)
Due to the shuttering of Google Code.
(由于Google Code的关闭。)
jquery-csv has moved to GitHub(jquery-csv已移至GitHub)