I can't get my head around this one guys. I have a CSV file which I read from via AJAX, and I am creating an array from what is returned. My CSV file looks like this:
ID,name,address
0,john,123 fake st
1,bruce,123 fake st
2,john,124 fake st
3,fred,125 fake st
4,barry,126 fake st
I call it via an ajax function:
if (window.XMLHttpRequest) {
var ajax = new XMLHttpRequest();
} else var ajax = new ActiveXObject("Microsoft.XMLHTTP");
function include(src) {
ajax.open('GET', src, false);
ajax.send(null);
return ajax.responseText;
}
and loop through it like so:
var bsf = include('csv.csv');
// construct an array from the first line of the file
// and use that array to name the keys in all further arrays
var cols = bsf.split('\r\n');
var ln1 = cols[0].split(',');
// pull out each line from bsf and turn it into an array
var line = [];
var table = {};
var curRow = [];
for (i = 1; i < cols.length; i++) { // i = 1 so we can skip the 'title' csv line
curRow = cols[i].split(',');
for (j = 0; j < curRow.length; j++) {
line[ln1[j]] = curRow[j];
}
table[curRow[0]] = line;
}
console.dir(table);
Instead of an object with one array for each row, I have 4 arrays that all contain the last row of the csv file. The nested for loop completes properly, and if I alert(line) before entering it into the table object, it returns the current line array correctly, but still does not assign that array to the object line.
Where I want
table{
0: [id: 0, name: 'john', address: '123 fake st'],
1: [id: 1, name: 'bruce', address: '124 fake st'],
...}
I get
table{
4: [id: 4, name: 'barry', address: '126 fake st'],
4: [id: 4, name: 'barry', address: '126 fake st'],
etc.}
Any ideas? I get the feeling I am assigning them all correctly throughout the loop, but then on the last run through I am assigning them all wrongly and overwriting the correct ones.
console.log(JSON.stringify(table));
(facepalm). @Black_Stormy you should not useArrays
where what you really want areObjects
(Hashes). – c69 Sep 9 '12 at 2:57