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?
i' symbol next toresultswhen it gets logged?i' is the browser's console telling you that that piece of data was evaluated when you went to look at in the console, and not when its line was reached. This means that (probably) it was empty whileprocess()was running, and it wasn't until afterwards when you inspected that it was actually populated.process()once allfr.onload()are finished.