For a script I am working I keep getting an array filled with 'undefined' instead of the actual values, I have a CSV file which im reading with $.ajax, I am trying to split the entire CSV into arrays based on the header row.
The code I have now:
$.ajax({
type: "GET",
url: "airport.txt",
dataType: "text",
success: function(data) {
lines = processData(data);
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(headers[j]+":"+data[j]);
}
lines.push(tarr);
}
}
lines.map(function(d){
country.push(d.headers);
});
console.log(country);
}
}
});
I think the issue lies within the country.push(d.headers);
I've tried several other options for the d.headers
such as d.lines
d.headers[0]
d.country
and d.data
.
What I want is for country
to be filled with headers[0]
which is the column labeled 'Country Code', but as soon as I change d.headers
into d.headers[0]
I get Uncaught TypeError: Cannot read property '0' of undefined
What is going wrong here and how can I best approach filtering the CSV file by column?
Edit:
With help of the plugin in the comments I have managed to make it work.
Should anyone else run into this, here is the code snippet I've used to make it work for me, it could probably be better but I'm not really advanced in JavaScript.
$(document).ready(function(){
//Read CSV
$.ajax({
type: "GET",
url: "airport.txt",
dataType: "text"
})
.done(function(data){
//process CSV Data
processCsv(data);
})
.fail(function(){
alert("Error: Failed to load data");
});
});
function processCsv(data){
//Read CSV Data into multidimensional Array
var array = $.csv.toArrays(data);
//Put headers in own array
var headers = array.splice(0,1);
//Make each header its own value
var headerString = headers.toString();
headers = headerString.split(',');
//separate all array values
var arrayString = array.toString();
array = arrayString.split(',');
return { header:headers, values:array};
}