简体   繁体   中英

How to give a custom name to the objects in an array?

I have an upload form and for adding and deleting the files in a filelist I created an array that contains the files to send them in one request.

Creating the array

var filelist = [];
for(var i = 0; i < data.files.length; i++){
   filelist.push(data.files[i]);
   console.log(filelist);
}

Result in console

[File, File, File]

The files are contained in the array but now I want to give the names in the array the names of the files for deleting purposes.

So instead of [File, File, File], I would like to have for example [image01.jpg, image02.jpg, image03.jpg]

I have already tried

filelist.push(data.files[i].name);

result

["image01.jpg", "image02.jpg", "image03.jpg"]

But the files aren't added to the array? Can anybody help me with this please? The reason I'm doing this is because I would like to try to remove files from the array on value and not on index.

code for deleting the files from the array

var idx = filelist.indexOf(file.name);
filelist.splice(idx,1);

You can set the name of the file as a key:

var filelist = {};
for(var i = 0; i < data.files.length; i++) {
   var file = data.files[i];
   filelist[file.name] = file;
}

And then use the delete operator to delete the file based on its name:

var filename = fileToDelete.name;
delete filelist[filename]; 

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