1

I want to transfer the images selected by the user to an object with javascript and read from there. I do this using the code below. When I print the productImages variable to the console, the data appears, but what should I do to read the data one by one?


let productImages = {};
var totalfiles = document.getElementById('uploadImages').files.length;
let x = 0;
for (var index = 0; index < totalfiles; index++) {
    var file = document.getElementById('uploadImages').files[index];
    if (file) {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = async function(e) {
            Image = e.target.result;
            productImages[x] = {'data': {'image': Image}};
            x++;
        };
    }
}
  • you can read productImages array one by one using map method, Can you add some sample array item ? – Asela Priyadarshana Dec 24 '21 at 07:03
  • ` { "0": { "data": { "image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAsCAYAAAC+GzLvAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAERJREFUeNpi+P//PwM2PGvWrP+45JgYyADDURMjKJRI1jUa5JQEOSg0RgNiVNOoplFNI0gTy+zZs0ku+EYLS0o0AQQYAPQZWT3gdMRjAAAAAElFTkSuQmCC" } }, "1": { "data": { "image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAsCAYAAAC+GzLvAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAERJREFUeNpi+P//PwM2PGvWrP+45JgYyADDURMjKJRI1jUa5JQEOSg0RgNiVNOoplFNI0gTy+zZs0ku" } } } ` –  Dec 24 '21 at 07:09
  • Add added answer according to your comment, check it – Asela Priyadarshana Dec 24 '21 at 07:20
  • I solved my problem, you can learn how I did it here [https://stackoverflow.com/questions/21518381/proper-way-to-wait-for-one-function-to-finish-before-continuing](https://stackoverflow.com/questions/21518381/proper-way-to-wait-for-one-function-to-finish-before-continuing) –  Dec 29 '21 at 09:52

1 Answers1

1

Try this way, to ready your productImages object

for (const image in productImages) {
  console.log(productImages[image].data);
}
  • unfortunately that didn't work, no data was written to the console –  Dec 24 '21 at 07:26
  • https://jsfiddle.net/93daor8z/1/ check this I use an object that you provided to me, also you can access the image URL by changing console.log as `productImages[image].data.image`, if that is not the solution please update console log result of productImages – Asela Priyadarshana Dec 24 '21 at 07:32
  • I can't do anything in the for loop. I guess it doesn't take the array size. When I do this manually, productImages[1] comes undefined `console.log(productImages); for (const image in productImages) { console.log(productImages); console.log(productImages[image].data.image); }` –  Dec 24 '21 at 07:50