Categories
JavaScript Answers

How to Loop Through Each Item in a JavaScript FileList?

Spread the love

Sometimes, we want to loop through each item in a JavaScript file list.

In this article, we’ll look at how to loop through each item in a JavaScript file list object.

Convert the FileList Object with the Array.from Method and Use the Array.prototype.forEach Method

One way to let us loop through each item in a file list object is to convert it to an array with the Array.from method.

Then we can use the forEach method on it to loop through the file list entries.

For instance, if we have the following file input:

<input type='file' multiple>

Then we can get the input and listen to the change event of the file input to get the selected files after they’re selected:

const input = document.querySelector('input');
input.addEventListener('change', () => {
  Array.from(input.files)
    .forEach(file => {
      console.log(file)
    });
})

The file input has the multiple attribute so that we can select multiple files.

We call addEventListener on the input to add a change listener to it.

We call Array.from method to convert the input.files file list to an array with the selected files.

input.files is the file list object with the selected files.

Then we can call the forEach method to loop through each file.

Convert the FileList Object with the Spread Operator and Use the Array.prototype.forEach Method

Another way to convert the file list object to an array is to use the spread operator.

This works since a file list is an iterable object.

For instance, we can write:

const input = document.querySelector('input');
input.addEventListener('change', () => {
  [...input.files]
  .forEach(file => {
    console.log(file)
  });
})

to spread the input.files entries into an array.

Then we can call forEach on it as we did before.

Use the for-of Loop

Since the file list object is an iterable object, we can also use the for-of loop on it to loop through each file list entry.

For instance, we can write:

const input = document.querySelector('input');
input.addEventListener('change', () => {
  for (const file of input.files) {
    console.log(file)
  }
})

to loop through each entry of input.files with the for-of loop.

Conclusion

We can convert the file list object to an array and use the forEach method or use the for-of loop to loop through each item in the file list.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *