Created
March 26, 2018 08:10
-
-
Save mfalade/d3a482378e1b46c924413709931dde83 to your computer and use it in GitHub Desktop.
CSV reader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function csv(text) { | |
var p = '', row = [''], ret = [row], i = 0, r = 0, s = !0, l; | |
for (l in text) { | |
l = text[l]; | |
if ('"' === l) { | |
if (s && l === p) row[i] += l; | |
s = !s; | |
} else if (',' === l && s) l = row[++i] = ''; | |
else if ('\n' === l && s) { | |
if ('\r' === p) row[i] = row[i].slice(0, -1); | |
row = ret[++r] = [l = '']; i = 0; | |
} else row[i] += l; | |
p = l; | |
} | |
return ret; | |
}; | |
$("#fileImportInput").on('change', function(changeEvent) { | |
$scope.$apply(function () { | |
$scope.rows = []; | |
$scope.objReps = []; | |
$scope.headers = []; | |
}); | |
const files = changeEvent.target.files; | |
if (files.length) { | |
const r = new FileReader(); | |
r.onload = function(e) { | |
const contents = e.target.result; | |
$scope.$apply(function () { | |
const rows = csv(contents) || []; | |
const headers = rows.shift(); | |
$scope.headers = headers; | |
$scope.objReps = []; | |
if (headers && headers.length > 0) { | |
$scope.rows = rows.map(function (row) { | |
const newRow = new Array(headers.length); | |
const objRep = { }; | |
for (var i = 0; i < row.length; ++i) { | |
newRow[i] = row[i]; | |
if (newRow[i] && newRow[i] !== "") { | |
objRep[headers[i]] = newRow[i]; | |
} | |
} | |
$scope.objReps.push(objRep); | |
return newRow; | |
}); | |
} | |
}); | |
}; | |
r.readAsText(files[0]); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment