如何将FileList对象转换为指定结构的对象数组
Convert FileList to Array of Keyed Objects
No problem at all—turning that FileList into your desired array format is super simple. Here's how you can do it:
Using Array.from() and map() (concise approach)
Since FileList is an iterable array-like object, we can convert it to a regular array and then map each file to an object with a dynamic key:
// Get your FileList from the input element const fileList = document.getElementById('your-file-input').files; // Convert to the desired array format const formattedArray = Array.from(fileList).map((file, index) => ({ [`file${index}`]: file }));
Breakdown of the code:
Array.from(fileList)converts the FileList into a standard JavaScript array so we can use array methods likemap().- The
map()function loops over each file in the array. For each file, we create a new object where the key isfilefollowed by the index (likefile0,file1), and the value is the actual File object. - The template literal
[`file${index}`]lets us dynamically create the object key based on the index.
Alternative: Using a for loop
If you prefer a more explicit loop approach, this works too:
const fileList = document.getElementById('your-file-input').files; const formattedArray = []; for (let i = 0; i < fileList.length; i++) { formattedArray.push({ [`file${i}`]: fileList[i] }); }
Either way, the result will be exactly the array you need: an array where each element is an object with a unique fileN key pointing to the corresponding File object, and no trace of the original FileList's length property.
内容的提问来源于stack exchange,提问作者NeERAJ TK
相关产品推荐
相关产品推荐

