Search code examples
javascriptjqueryhtmlobjectfilelist

Merging/combining Filelist


I've got two Filelist objects containing multiple files in a same form and I want to merge it.

  var data1 = $('#one')[0].files;
  var data2 = $('#two')[0].files;
  console.log(data1);
  console.log(data2);
  var obj = $.merge(data1,data2);
  console.log(obj);

I tried $.merge and $.extend, the result obj seems have all the files, but the length of it is incorrect:

FileList {2: File, 3: File, 0: File, 1: File, length: 2}

jsFiddle: https://jsfiddle.net/nxtdnhgu/


Solution

  • From jquery documentation.

    The $.merge() function is destructive. It alters the length and numeric index properties of the first object to include items from the second.

    If you need the original first array, make a copy of it before calling $.merge().

    var obj = $.merge( $.merge( [], data1 ), data2 );
    

    Working js fiddle: https://jsfiddle.net/t1n08ykd/