I need to upload multiple json files and store their contents in an array. My goal is to somehow merge them together. I tried doing this:
var results = new Array(); //global variable
document.getElementById('uploadId').onclick = function () {
var files = document.getElementById('selectFiles').files;
for (var i = 0; i < files.length; i++) {
var fr = new FileReader();
fr.onload = function (e) {
console.log(e);
var result = JSON.parse(e.target.result);
results.push(result);
}
fr.readAsText(files.item(i));
}
process();
};
function process(){
console.log(results); // displays everything as expected
console.log(results.length); // returns 0 ?!
console.log(results[0]) // return undefined ?!
}
then while logging the results
array into console, everything displays as expected. But when I try to iterate through the array, all the individual objects are undefined
. And results.length
returns 0
as well.
I guess there might be a problem connected to the asynchronicity. Any idea how to solve this?