257

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?

alex
  • 7,111
  • 15
  • 50
  • 77

7 Answers7

430

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 => { ... });
Amadan
  • 191,408
  • 23
  • 240
  • 301
60

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]);
}
Willian Ribeiro
  • 715
  • 5
  • 7
51

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

dude
  • 5,678
  • 11
  • 54
  • 81
  • This is not a destructuring assignment. It’s [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). It will create a new array just for this operation. – Daniel B Feb 07 '22 at 20:09
  • I realise the original question wasn't about `map()` but 95% of my array iterations are `map`/`filter`/`some` etc. so this would be my preferred solution – Andy Apr 08 '22 at 16:19
5

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
})
Mohoch
  • 2,633
  • 1
  • 26
  • 26
2

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);
   }
}
Balaj Khan
  • 2,490
  • 2
  • 17
  • 30
1

Use for...of loop:

for (const file of fileList) {
  // ...
}
Mir-Ismaili
  • 13,974
  • 8
  • 82
  • 100
-6

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);
}
Balaj Khan
  • 2,490
  • 2
  • 17
  • 30