fightstarr20 fightstarr20 - 3 years ago 207
Javascript Question

Read CSV file and output results as HTML list

I am trying to read in a CSV file using PapaParse and then output it as a html list. I have this so far...

document.getElementById('txtFileUpload').addEventListener('change', upload, false);

function upload(evt) {

var data = null;
var file = evt.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var csvData = event.target.result;
var data = Papa.parse(csvData, {header : true});

console.log(data.data);

var arrayLength = data.data.length;
console.log(arrayLength);
for (var i = 0; i < arrayLength; i++) {
console.log(data.data[i]);
$("#header").append("<li>" + data.data[i] + "</li>");
}

};
reader.onerror = function() {
alert('Unable to read ' + file.fileName);
};

}


This works but each list item outputs as [object Object]. Where am I going wrong?

My console output looks like this...

enter image description here

Answer Source

You have an array of objects, thus when you do

"<li>" + data.data[i] + "</li>"

those objects are converted to strings. Plain object's toString representation is [object Object].

From your question it's unclear what do you expect, so you could either get object's apple field:

"<li>" + data.data[i].apple + "</li>"

or use JSON representation of this object:

"<li>" + JSON.stringify(data.data[i]) + "</li>"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download