简体   繁体   中英

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

scripts.js

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`; <------
  });                                                  <-----
  console.log(files);
};

I'm getting this as an output of files variable value in console. 这是我在文件中得到的(对象列表)

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: https://developer.mozilla.org/en-US/docs/Web/API/File#instance_properties ). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM