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
:
How to properly loop through field.photo.files
?
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 => { ... });
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
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);
}
}
Array.prototype.forEach.call(field.photo.files, file => console.log(file));
– Tolgahan Albayrakfield.photo.files
is an object prototyped onFileList
; just likeHTMLCollection
, it does not haveArray.prototype
in its prototype chain. – Amadanfor loop
work :) – Reza