1

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);
DC2015
  • 51
  • 7
  • Possible duplicate of [JavaScript Array Push key value](http://stackoverflow.com/questions/7813374/javascript-array-push-key-value) – Plummer Nov 09 '15 at 20:15
  • JavaScript arrays have numeric keys. That is, the keys to the entries are `0`, `1`, `2`, and so on. If you want general string keys, use a plain object. – Pointy Nov 09 '15 at 20:20

1 Answers1

4

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]; 
John Bupit
  • 10,406
  • 8
  • 39
  • 75
  • You can indeed do this, but then you're not using the array as an array and it might as well be a plain object. If you use an array and try to serialize it in anyway (say, as a parameter in an ajax call), this won't work. – Pointy Nov 09 '15 at 20:19
  • Result of your possible solution is[Serene-Video-232.jpg: File, Serene-Video-233.jpg: File] But it doesn't delete the file from the array – DC2015 Nov 09 '15 at 20:21
  • @DC2015 this is how your console prints out the key value pairs. But, like Pointy points out, you might as well make `filelist` a JavaScript object. – John Bupit Nov 09 '15 at 20:27
  • at John Bupit: It works but as "Pointy" mentioned it doesn't work as a parameter in an ajax call. at Pointy: Do you maybe have an alternative? – DC2015 Nov 09 '15 at 20:29