Can't use forEach with Filelist

JavascriptFile

Javascript Problem Overview


I'm trying to loop through a Filelist:

console.log('field:', field.photo.files)
field.photo.files.forEach(file => {
   // looping code
})

As you can see field.photo.files has a Filelist:

enter image description here

How to properly loop through field.photo.files?

Javascript Solutions


Solution 1 - Javascript

A FileList is not an Array, but it does conform to its contract (has length and numeric indices), so we can "borrow" Array methods:

Array.prototype.forEach.call(field.photo.files, function(file) { ... });

Since you're obviously using ES6, you could also make it a proper Array, using the new Array.from method:

Array.from(field.photo.files).forEach(file => { ... });

Solution 2 - Javascript

You can also iterate with a simple for:

var files = field.photo.files;

for (var i = 0; i < files.length; i++) {
    console.log(files[i]);
}

Solution 3 - Javascript

In ES6 you can use:

[...field.photo.files].forEach(file => console.log(file));

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Solution 4 - Javascript

The lodash library has a _forEach method that loops through all collection entities, such as arrays and objects, including the FileList:

_.forEach(field.photo.files,(file => {
     // looping code
})

Solution 5 - Javascript

The following code is in Typescript

urls = new Array<string>();

detectFiles(event) {
   const $image: any = document.querySelector('#file');
   Array.from($image.files).forEach((file: any) => {
      let reader = new FileReader();
      reader.onload = (e: any) => { this.urls.push(e.target.result); }
      reader.readAsDataURL(file);
   }
}

Solution 6 - Javascript

If you are using Typescript you can do something like this: For a variable files with a type FileList[] or File[] use:

for(let file of files){
    console.log('line50 file', file);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalexView Question on Stackoverflow
Solution 1 - JavascriptAmadanView Answer on Stackoverflow
Solution 2 - JavascriptWillian RibeiroView Answer on Stackoverflow
Solution 3 - JavascriptdudeView Answer on Stackoverflow
Solution 4 - JavascriptMohochView Answer on Stackoverflow
Solution 5 - JavascriptShalabh ShankhdharView Answer on Stackoverflow
Solution 6 - JavascriptVictor Hugo Arango A.View Answer on Stackoverflow