0

I have a input form file picker which returns the following object output :

enter image description here

Image as text ->

FileList {0: File, 1: File, length: 2}
0: File {name: "Screenshot 2021-02-19 at 12.27.47 PM.png", lastModified: 1613717870763, lastModifiedDate: Fri Feb 19 2021 12:27:50 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 81142, …}
1: File {name: "Screenshot 2021-02-18 at 12.11.00 PM.png", lastModified: 1613630510734, lastModifiedDate: Thu Feb 18 2021 12:11:50 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 128961, …}
length: 2

I need to convert it to an array of objects of the form :

[{file0: file}, {file1: file}]

Please note that I don't need the length item present in the initial object in the final array

10
  • 1
    Please don't present text as an image. Commented Feb 19, 2021 at 13:48
  • What did you try so far? Commented Feb 19, 2021 at 13:48
  • 5
    Are you sure that you want a different property name inside each of the objects in the output array? I would hate it if someone fed me that kind of data... I would recommend trying var arr = Array.from(theFileList) and see if that works for you. Commented Feb 19, 2021 at 13:51
  • 1
    I agree with PeterB: that is a horrible choice for an output format. You don't need those numerical suffixes... you already know the index from the position they have in the array. Commented Feb 19, 2021 at 13:52
  • 1
    As a comment on: "I need to convert it to an array of objects" and "note that I don't need the length item present in the initial object in the final array" An array always has a (non-enumerable) length property. Which will automatically be set to 2 if you have an array with 2 elements. Commented Feb 19, 2021 at 14:11

2 Answers 2

2
const objOfObjs = {
   "one": {"id": 3},
   "two": {"id": 4},
};

const arrayOfObj = Object.entries(objOfObjs).map((e) => ( { [e[0]]: e[1] } ));

i think it work for you.

Sign up to request clarification or add additional context in comments.

1 Comment

Altered it to : const res = Object.entries(files).map((e) => ({ [file${e[0]}]: e[1] }));
1

You could do with Array#map

const arr = [{name:1},{name:2}];

const res =  arr.map((item,ind)=>({[`file${ind}`]:item}));

console.log(res)

1 Comment

A FileList does not have the map method. Use Array.from(fileList).map(...) instead. Or skip the map call, and pass the callback as second argument to Array.from() eg. Array.from(fileList, (file, i) => { [`file${i}`]: file })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.