Skip to content

how to set a value of a key of an array object in javascript?

I’m creating a drag and drop files(multiple files can be selected) feature. WHere user can select multiple files.I want to convert the size of file from byte to mb. . the function to get all the files


const handleFiles = (files) => {
  files = [...files];

//converting bytes into mb and trying to assign it back to size key
  files.forEach(function (file) {                      <----these lines need to be changed
    file["size"] = `${(file["size"] / 1024 ** 2).toFixed(2)} mb`; <------
  });                                                  <-----

I’m getting this as an output of files variable value in console. this is what i'm getting in files(a list of objects)

Why i’m using spread operator?

Ans: If i don’t use the spread operator and user select only one file then it is passed as an object and not as a list of object

How can i set the value of each size key of an object with new value.


File.size is a read-only property, you cannot change it (see here: If you want to show file size in Mb in your UI, you will have to get the File.size (or File[“size”], like you are doing), and process it like you do in your function to show it in the UI (have the function return an array of sizes, or include the size formatting in the rendering part of your app), but you cannot change the property on the File instances themselves.