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++;
        };
    }
}
4
  • you can read productImages array one by one using map method, Can you add some sample array item ? Commented Dec 24, 2021 at 7: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" } } } ` Commented Dec 24, 2021 at 7:09
  • Add added answer according to your comment, check it Commented Dec 24, 2021 at 7: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 Commented Dec 29, 2021 at 9:52

1 Answer 1

1

Try this way, to ready your productImages object

for (const image in productImages) {
  console.log(productImages[image].data);
}
Sign up to request clarification or add additional context in comments.

3 Comments

unfortunately that didn't work, no data was written to the console
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
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); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.