I am using jquery.csv to parse a csv file and show the data in a table format.
my csv file data: test.csv
header1, header2, header3, header4
value1, value2, value3, value4
value1, value2, value3, value4.1,value4.2,value4.3
value1, value2, value3, value4
My code: index.html
var data;
$.ajax({
type: "GET",
url: "test.csv",
dataType: "text",
success: function(response) {
data = $.csv.toObjects(reponse);
// generating the table for user view
generateTable(data);
var html = generateTable(data);
$('#result').html(html);
}
});
function generateTable(data) {
var html = '';
if (typeof(data[0]) === 'undefined') {
return null;
}
if (data[0].constructor === Object) {
for (var row in data) {
html += '<tr>\r\n';
for (var item in data[row]) {
html += '<td>' + item + ':' + data[row][item] + '</td>\r\n';
}
html += '</tr>\r\n';
}
}
return html;
}
The code doesnt generate an error and it shows in the table that i print is one value per header, but I would want to know how can I get several value per header? Like for header4 there are several values and I would want all values in the cell for header4.
Or if you can suggest any better way of parsing this kind of data I would appreciate it. thanx!
JSFiddle
So... Now I understood your question, hehe. Here we go:
You can't do what you want just using the default parser. So you should create your own parser with
$.csv.parsers.splitLineshelper (you can read about that there). So you can do whatever you want to do with those values of overflow cases. In your case, you want to use the last "column header" as the header of those values, right? That's happening on this line:If that column exists on the header definition, it'll call the header name. If doesn't, it'll call the last header name. That's it?